[英]How to retrieve an item from a ListPickerFlyout?
I created a ListPickerFlyout and I would like, through a button, select an item from the list. 我创建了一个ListPickerFlyout,我想通过一个按钮从列表中选择一个项目。 In XAML I have done so: 在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>
in c # I want to recover the selected item, and then do some operations. 在C#中,我要恢复选定的项目,然后执行一些操作。 MSDN there is SelectedItem instead I can not find it, and I said that does not exist, how could I do? 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();
}
Add a property of your object to your view model (or code behind, or whatever you use as your datacontex), and then add a binding to that on that list. 将对象的属性添加到视图模型(或后面的代码,或用作数据上下文的任何内容),然后在该列表上添加绑定。
Assuming you have public MyObject my_object {get;set;}
in your datacontext, you should have on your xaml something like: 假设您在数据public MyObject my_object {get;set;}
有public MyObject my_object {get;set;}
,则在xaml上应该有以下内容:
<ListPickerFlayout ...
SelectedItem = {binding my_object;} />
This way it knows that whatever is selected, will be that object in the data context, and you can access it from your code, by simply using the above property: 这样,它便知道无论选择什么,该对象都将是数据上下文中的那个对象,您只需使用上面的属性就可以从代码中访问它:
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();
}
}
Alternatively, as this msdn suggests, you won't have to bind to a property (i would, since i'll try to do it in a MVVM way), and all you'll have to do is cast the sender and use it's selected item, something along: 或者,如此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() + ".";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.