2013-03-07 57 views
0

我有兩個視圖模型,第一個視圖模型我有一個列表框:的SelectedItem必須始終設置爲有效值

<ListBox x:Name="MainMenu" toolkits:TiltEffect.IsTiltEnabled="True" 
SelectedItem="{Binding SelectedItem, Mode=TwoWay}" 
ItemTemplate="{StaticResource MainMenu}" 
ItemsSource="{Binding Categories}" Margin="0,97,0,0" 
Tap="MainMenu_Tap"> 

在第二頁,我有一個listpicker

<toolkit:ListPicker Margin="0,153,0,0" Background="{StaticResource PhoneAccentBrush}" VerticalAlignment="Top" 
ItemsSource="{Binding Categories}" 
SelectedItem="{Binding Item}" 
ItemTemplate="{StaticResource CategorySelector}" 
FullModeHeader="Category" 
FullModeItemTemplate="{StaticResource FullCategorySelector}" 
BorderBrush="{StaticResource PhoneAccentBrush}"/> 

什麼我想要的是當我導航到第二頁時,第一頁中的選定項目將在第二頁中選擇。但是當我導航到第二頁時,我總是得到所選項目必須始終設置爲有效值。

第一視圖模型

private CategoryModel _selectedItem = null; 
public CategoryModel SelectedItem 
{ 
    get { return _selectedItem; } 
    set 
    { 
     if (_selectedItem == value) 
     { 
      return; 
     } 

     var oldValue = _selectedItem; 
     _selectedItem = value; 

     RaisePropertyChanged("SelectedItem", oldValue, value, true); 
    } 
} 

第二視圖模型

private CategoryModel _item = null; 
public CategoryModel Item 
{ 
    get { return _item; } 
    set 
    { 
     if (_item == value) 
     { 
      return; 
     } 

     var oldValue = _item; 
     _item = value; 

     // Update bindings, no broadcast 
     RaisePropertyChanged("Item"); 
    } 
} 

enter image description here

EDIT

當我將第二頁中的listpicker更改爲Listbox時,它工作得很好。

所以這是一個問題enter link description here。我應該怎麼做才能使這個東西與listpicker一起工作?

回答

0

我認爲你是混淆視圖和viewmodels。

由於您在XAML中綁定了選定的項目,因此當解析XAML並創建頁面時,它試圖綁定到尚未創建的集合中的項目。這就是爲什麼在代碼背後設置這個錯誤時的意見提示解決方法。

在第一頁的Tap處理程序中,我假設您將所選項目的一些細節傳遞到第二頁。因此,您可以刪除所選項目的XAML綁定,並在第二頁的OnNavigatedTo事件處理程序中設置代碼中的綁定,一旦知道已填充ItemsSource。

或者,您可以考慮讓這兩個頁面共享相同的viewmodel實例。

0

ListPicker使用Items.IndexOf來獲取應該選擇的項目實例的索引。

如果實例不匹配(它不是集合中的對象實例),IndexOf將返回-1,並且引發InvalidOperationException異常:「SelectedItem必須始終設置爲有效值」。

覆蓋集合中類型的Equals方法,它將按預期工作。

例子:

public override bool Equals(object obj) 
{ 
     var target = obj as ThisTarget; 
     if (target == null) 
      return false; 

     if (this.ID == target.ID) 
      return true; 

     return false; 
} 

希望它可以幫助

相關問題