2014-02-18 138 views
0

我有一個組合框綁定到一個可以正常工作的Observable集合。在頁面加載時,未設置Combobox的選定項目。用戶可以從Combobox中選擇一個項目。刪除Combobox SelectedItem WPF MVVM

但是,我希望能夠通過點擊按鈕取消選擇所選項目。有沒有辦法用MVVM模式來做到這一點?我真的不想在Observable Collection的開頭插入一個NULL項。

到目前爲止,我已經打破與視圖中的代碼隱藏按鈕單擊事件MVVM模式實現了這個...

private void ClearPublicationsButton_Click(object sender, RoutedEventArgs e) 
    { 
     comboBox1.SelectedItem = null; 
    } 

感謝

+1

有一個屬性綁定SelectedItem的Combobox ..有一個命令按鈕點擊..在按鈕點擊,你可能有你的viewmodel組合框的集合..在這一點上,你可以通過傳遞屬性與Combobox的SelectedItem綁定..... – Sankarann

+0

http://stackoverflow.com/questions/12644140/deselecting-comboboxitems-in-mvvm – samar

回答

0

在視圖模型,這暴露了集合:

public MyMasterViewModel() 
{ 
    ClearSelectionCommand = new RelayCommand(
     () => SelectedNestedViewModel = null, 
     () => SelectedNestedViewModel != null); 
} 

public ObservableCollection<MyNestedViewModel> NestedViewModels { /* ... */ } 

public MyNestedViewModel SelectedNestedViewModel 
{ 
    get { return selectedNestedViewModel; } 
    set 
    { 
     if (selectedNestedViewModel != value) 
     { 
      selectedNestedViewModel = value; 
      OnPropertyChanged("SelectedNestedViewModel"); 
     } 
    } 
} 
private MyNestedViewModel selectedNestedViewModel; 

public ICommand ClearSelectionCommand { get; private set } 

在XAML:

<Button Command="{Binding ClearSelectionCommand}" Content="Clear selection"> 
<ComboBox ItemsSource="{Binding NestedViewModels}" SelectedItem="{Binding SelectedNestedViewModel}">