我创建了一个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();
}
答案 0 :(得分:0)
将对象的属性添加到视图模型(或后面的代码,或者用作datacontex的任何内容),然后在该列表中添加绑定。
假设你的datacontext中有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方式进行),而且你所有&# 39; ll必须要做的是投射发件人并使用它所选择的项目,其中包括:
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() + ".";
}