0

我有一个绑定到 Item 对象集合的 WPF 数据网格。数据网格有一个复选框列。我想实现它,以便当从任何行选中/取消选中复选框时,选中/取消选中所有其他行。有没有好的 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
}
4

1 回答 1

1

基于先前的答案

将其用作您的数据项:

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;
       }
    }
}
于 2013-08-30T16:30:13.677 回答