我使用MVVM
模式將Observable集合綁定到combobox
。我可以成功綁定到combobox
,但現在我正在尋找一種方法在我的視圖中獲取SelectedItem
屬性模型(我不能簡單地調用它,因爲那將制動模式)我想象它的方式是,必須有某種方式XAML
指向所選擇的項目,我可以在我的視圖模型以後用它來創建一個綁定。我似乎無法弄清楚是怎麼...使用MVVM模式獲取WPF組合框SelectedItem屬性
我如何能做到這一點有什麼建議?
XAML
<ComboBox SelectedIndex="0" DisplayMemberPath="Text" ItemsSource="{Binding Path=DocumentTypeCmb,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
Grid.Column="1" Grid.Row="4" Margin="0,4,5,5" Height="23"
HorizontalAlignment="Left" Name="cmbDocumentType" VerticalAlignment="Bottom"
Width="230" />
代碼
//Obesrvable collection property
private ObservableCollection<ListHelper> documentTypeCollection = new ObservableCollection<ListHelper>();
public ObservableCollection<ListHelper> DocumentTypeCmb
{
get
{
return documentTypeCollection;
}
set
{
documentTypeCollection = value;
OnPropertyChanged("DocumentTypeCmb");
}
}
//Extract from the method where i do the binding
documentTypeCollection.Add(new ListHelper { Text = "Item1", IsChecked = false });
documentTypeCollection.Add(new ListHelper { Text = "Item2", IsChecked = false });
documentTypeCollection.Add(new ListHelper { Text = "Item3", IsChecked = false });
DocumentTypeCmb = documentTypeCollection;
//Helper class
public class ListHelper
{
public string Text { get; set; }
public bool IsChecked { get; set; }
}
完美非常感謝您 –
+1,但設置的ItemsSource時請擺脫模式=雙向的 - 只是沒有任何意義。 – blindmeis
@blindmeis - 這是非常真實的,我只是從OP的樣本中複製/粘貼該部分。雖然它可能是默認的綁定模式,它不是完全* *不好明確地指定了 - 至少其他開發人員的閱讀代碼就沒有什麼是怎麼回事疑問(我已經看到了非常糟糕的生產WPF代碼之前在那裏新開發者沒有線索)。 – slugster