2010-11-12 122 views
1

我正在研究我的第一个WP7应用程序,这个问题让我头疼。如何将SelectedItem(从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-属性不会得到更新。这个函数没有实现(就像在WPF中)还是我只是在做一些事情? :-)

回答

6

只需使用 -

SelectedItem="{Binding MySelectedItem, Mode=TwoWay}",它应该是罚款。

+0

很酷,谢谢! – 2010-11-12 20:18:27

+0

我无法在WP7项目上使用此工作。任何人都可以验证这是否可以在Windows Phone 7上运行? – SondreB 2011-01-12 09:36:01

+0

我想知道,应该如何工作,因为ListBox的SelectedItems属性是只读属性。它假设抛出一个异常,如“不能设置只读属性System.Windows.Controls.ListBox.SelectedItems”。“ – derSteve 2012-05-21 19:27:58

0

您可能必须为您的列表框设置IsSynchronizedWithCurrentItem="True"

+0

不幸的是,不允许设置为“真”。 – 2010-11-12 19:31:52

+0

不,Windows Mobile 7使用Silverlight 3的某些版本:-) – 2010-11-12 20:22:55

0

这是我的解决方法..我希望有人会发布更优雅的解决方案。

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]; 
    } 

也许这会帮助别人的同时。

相关问题