【问题标题】:How to use calculated columns in DataGrid without usage XAML?如何在不使用 XAML 的情况下使用 DataGrid 中的计算列?
【发布时间】:2016-08-11 14:39:55
【问题描述】:

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

}

【问题讨论】:

  • 你问的是bindings吗?
  • 我使用绑定来创建这样的网格数据。但是我不明白,为什么在编辑例如RChanel的情况下,ItemColor没有更新
  • ItemColor 没有实现 INotifyPropertyChanged
  • 但这取决于其他属性。

标签: c# wpf datagrid


【解决方案1】:

我认为在 ViewModel 中使用 Brush 不是一个好主意(谈论 MVVM),而是使用 multiconverter 或 e.g. 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
}

【讨论】:

  • 我已添加通知。但我不明白,谁应该处理通知以及如何处理
  • 你说“我使用绑定来创建这样的网格数据”,所以我假设你有DataGrid.ItemsSource绑定到ObservableCollection<ColorItem>的属性(如果集合没有改变,然后一个简单的List<ColorItem> 就可以了)。如果这是真的,那么你只缺少INotifyPropertyChanged。这就是我的答案。
  • 是的,你是对的。我有 DataGrid.ItemsSource 作为 ObservableCollection.
  • 有效吗?也许您对 xaml(显示它)或绑定(显示您要绑定的属性)有问题。
  • 不要直接设置DataSource。使用绑定(在 xaml 中或在后面的代码中)。
猜你喜欢
  • 2018-05-19
  • 2019-01-07
  • 2018-03-21
  • 2017-05-16
  • 2019-04-02
  • 2010-11-12
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
相关资源
最近更新 更多