2013-08-30 75 views
0

我有一個綁定到Item對象集合的WPF數據網格。該數據網格有一個複選框列。我想實現它,以便在任何行中選中/取消選中複選框時,所有其他行都將被選中/取消選中。有沒有一種好的MVVM方式來做到這一點?WPF Datagrid - 如何在一行中進行更改會影響其他行

XAML

<DataGrid ItemsSource="{Binding Items}"> 
    <DataGrid.Columns> 
     <DataGridCheckBoxColumn Binding="{Binding MyProperty}" /> 
    <DataGrid.Columns> 
</DataGrid> 

C#

public class DataGridViewModel 
{ 
    public ObservableCollection<Item> Items { get; set; } 
} 

public class Item 
{ 
    public bool MyProperty { get; set; } // Set all Item.MyProperties when any are set 
} 

回答

1

基於一個Previous Answer

以此作爲你的數據項:

public class Selectable<T>: ViewModelBase //ViewModelBase should Implement NotifyPropertyChanged. 
{ 
    private T _model; 
    public T Model 
    { get { return _model; } 
     set 
     { 
      _model = value; 
      NotifyPropertyChange("Model"); 
     } 
    } 

    private bool _isSelected; 
    public bool IsSelected 
    { 
     get { return _isSelected; } 
     set 
     { 
      _isSelected = value; 
      NotifyPropertyChange("IsSelected"); 

      if (OnIsSelectedChanged != null) 
       OnIsSelectedChanged(this); 
     } 
    } 

    public Action<Selectable<T>> OnIsSelectedChanged; 
} 

然後改變你的ViewModel看起來像這樣:

public class DataGridViewModel 
{ 
    public ObservableCollection<Selectable<Item>> Items { get; set; } 

    public void SomeMethod() 
    { 
     Items = new ObservableCollection<Selectable<Item>>(); 

     //Populate the Collection here! 

     foreach (var item in Items) 
      item.OnIsSelectedChanged = OnItemSelectedChanged; 
    } 

    private void OnItemSelectedChanged(Selectable<Item> item) 
    { 
     if (item.IsSelected) 
     { 
      var itemsToDeselect = Items.Where(x => x != item); 

      foreach (var itemToDeselect in itemsToDeselect) 
       itemToDeselect.IsSelected = false; 
     } 
    } 
} 
相關問題