![](/img/trans.png)
[英]How to bind a Combobox to an ObservableCollection with SelectedItem dependant on ListBox?
[英]How to bind SelectedItem (from a ListBox) to a Variable?
我正在第一个WP7应用程序上工作,这个问题使我有些头疼。
我有一个这样定义的ListBox
<ListBox Grid.Row="1" ItemsSource="{Binding MyItemList}" SelectedItem="{Binding MySelectedItem}">
<ListBox.ItemTemplate>
<DataTemplate >
<StackPanel>
<TextBlock Text="{Binding Name}" FontSize="35" />
<TextBlock Text="{Binding Details}" FontSize="15"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
绑定ItemsSource可以正常工作,但是选择项目时MySelectedItem-Property不会更新。 是否未实现此功能(例如在WPF中),或者我只是在做某事? :-)
只需使用-
SelectedItem="{Binding MySelectedItem, Mode=TwoWay}"
,应该没问题。
您可能必须为ListBox设置IsSynchronizedWithCurrentItem="True"
。
这是我的解决方法。我希望有人发布更好的解决方案。
XAML:
<ListBox Name="DecksListBox" ItemsSource="{Binding MyItemsList}"
SelectionChanged="UpdateSelectedItem"
后台代码:
private void UpdateSelectedItem(object sender, SelectionChangedEventArgs e)
{
// Ignore if there is no selection
if (DecksListBox.SelectedIndex == -1)
return;
App.ViewModel.MySelectedItem = App.ViewModel.MyItemsList[DecksListBox.SelectedIndex];
}
也许这可能同时对某人有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.