如何在不使用XAML的情况下在DataGrid中使用计算列
本文关键字:DataGrid 计算 情况下 XAML | 更新日期: 2023-09-27 18:01:52
我有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; }
}
我不认为在ViewModel中使用Brush
(谈论MVVM)是一个好主意,而是使用多转换器或例如Color
+ ColorToSolidBrushConverter
。
但是在任何情况下,当你改变属性时,你不会发出通知,所以视图不知道什么时候更新。
固定版本: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
}