2010-11-12 46 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]; 
    } 

也許這會幫助別人的同時。

相關問題