WPF Datagrid - 如何在一行中进行更改会影响其他行

时间:2013-08-30 15:59:12

标签: c# wpf mvvm datagrid

我有一个绑定到Item对象集合的WPF数据网格。 datagrid有一个复选框列。我想实现它,以便当从任何行选中/取消选中复选框时,将检查/取消选中所有其他行。有没有一个好的MVVM方法呢?

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 个答案:

答案 0 :(得分: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;
       }
    }
}