如何从ListPickerFlyout中检索项
本文关键字:检索 ListPickerFlyout | 更新日期: 2023-09-27 18:00:03
我创建了一个ListPickerFlyout,我想通过一个按钮从列表中选择一个项目。在XAML中,我做到了:
<Button x:Name="BottoneFiltraCittaNotizie" Click="BottoneFiltraCittaNotizie_Click" Style="{StaticResource ButtonSearchStyle}" Grid.Row="0" BorderBrush="{x:Null}" Foreground="Gray" Margin="0,-12,0,0">
<Button.Flyout>
<ListPickerFlyout ItemsSource="{Binding Source={StaticResource Museum}}">
<ListPickerFlyout.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding NomeProvincia}" HorizontalAlignment="Left"/>
</StackPanel>
</DataTemplate>
</ListPickerFlyout.ItemTemplate>
</ListPickerFlyout>
</Button.Flyout>
</Button>
在c#中,我想恢复所选项目,然后进行一些操作。MSDN有SelectedItem,我找不到它,我说它不存在,我该怎么办?
private void BottoneFiltraCittaNotizie_Click(object sender, RoutedEventArgs e)
{
Regioni region = ListPickerFlyout.SelectedItem as Regioni; //ERROR!!
string regione = region.NomeRegione;
var GruppiAllNEWS = NotizieFB.Where(x => x.TAG.Contains(regione)).OrderBy(x => x.Data).Reverse();
}
将对象的属性添加到视图模型(或代码隐藏,或用作数据上下文的任何内容),然后在该列表中添加绑定。
假设您的数据上下文中有public MyObject my_object {get;set;}
,那么您的xaml上应该有以下内容:
<ListPickerFlayout ...
SelectedItem = {binding my_object;} />
通过这种方式,它知道无论选择什么,都将是数据上下文中的对象,并且您可以通过简单地使用上面的属性从代码中访问它:
public class SomeClass {
// this is your code behind file
public MyObject my_object {get;set;}
// this is where you go when you hit the button
OnButtonClick(sender, event) {
//my_object is accessible here. Assuming it has a DoSomething method, you can:
my_object.DoSomething();
}
}
或者,正如这个msdn所建议的,你不必绑定到一个属性(我会绑定的,因为我会尝试以MVVM的方式绑定),你所要做的就是转换发送者并使用它所选择的项目,类似于
void PrintText(object sender, SelectionChangedEventArgs args)
{
// get your object with the cast, and then get it's item
ListBoxItem lbi = ((sender as ListBox).SelectedItem as ListBoxItem);
// then you can use it like:
tb.Text = " You selected " + lbi.Content.ToString() + ".";
}