如何在不使用XAML的情况下在DataGrid中使用计算列?

时间:2016-08-11 14:39:55

标签: c# wpf datagrid

我有5列的DataGrid。某些列的值取决于其他列。如何创建这种依赖?我试图实现这个填充数据网格的结构。但是在其他细胞被编辑的情况下没有更新。

public class ColorItem
{
    //  Constructor
    /*
     *      ColorItem constructor
     *      Params: color name, color
     */
    public ColorItem(string color_name, Color color)
    {
        ItemName = color_name;
        RChanel = color.R;
        GChanel = color.G;
        BChanel = color.B;
    }

    //  Item name
    public string ItemName { get; set; }
    //  Item color (calculated item)
    public Brush ItemColor { get { return new SolidColorBrush(Color.FromRgb(RChanel, GChanel, BChanel)); } }
    //  Item r chanel
    public byte RChanel { get; set; }
    //  Item g chanel
    public byte GChanel { get; set; }
    //  Item b chanel
    public byte BChanel { get; set; }

}

1 个答案:

答案 0 :(得分:1)

我认为在ViewModel中使用Brush(谈论MVVM)并不是一个好主意,而是使用多路转换器,例如Color + ColorToSolidBrushConverter

但是在任何情况下,当您更改属性时都不会发出通知,因此View不知道何时更新。

修正版:

public class ColorItem : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged([CallerMemberName] string property = "") =>
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));

    public Brush ItemBrush => new SolidColorBrush(Color.FromRgb(R, G, B));

    byte _r;
    public byte R 
    {
        get { return _r; }
        set
        {
            _r = value;
            OnPropertyChanged(); // this will update bindings to R
            OnPropertyChanged(nameof(ItemBrush)); // this will update bindings to ItemBrush
        }
    }

    ... // same for G and B
}
相关问题