简体   繁体   English

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

[英]WPF Datagrid - How to make a change in one row affect other rows

I have a WPF datagrid that is bound to a collection of Item objects. 我有一个WPF数据网格,它绑定到Item对象的集合。 The datagrid has a checkbox column. 该数据网格具有一个复选框列。 I would like to implement it so that when the checkbox is checked/unchecked from any row, all other rows are checked/unchecked. 我想实现它,以便当从任何行中选中/取消选中该复选框时,所有其他行都处于选中/未选中状态。 Is there a good MVVM way to do this? 有没有很好的MVVM方法可以做到这一点?

XAML XAML

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

C# 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
}

Based on a Previous Answer : 根据先前的答案

Use this as your data items: 将此用作您的数据项:

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;
 }

Then change your ViewModel to look like so: 然后将您的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;
       }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM