【问题标题】:Changing color of rows in datagrid from itemSource从 itemSsource 更改数据网格中行的颜色
【发布时间】:2018-10-22 12:03:04
【问题描述】:

在我的数据网格中,我有代表不同颜色的行。 RGB 格式。

我要做的基本上是将每一行的颜色设置为项目所代表的颜色。

所以我想循环遍历行并根据它持有的项目设置颜色。

我的模型如下所示:

public class ColorModel : INotifyPropertyChanged
{
    private int _GreenValue;
    private int _RedValue;
    private int _BlueValue;

    public int GreenValue
    {
        get { return _GreenValue; }
        set
        {
            if (_GreenValue != value)
            {
                _GreenValue = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("GreenValue"));
                }
            }
        }
    }


    public int RedValue
    {
        get { return _RedValue; }
        set
        {
            if (_RedValue != value)
            {
                _RedValue = value;
                PropertyChanged(this, new PropertyChangedEventArgs("RedValue"));
            }
        }
    }


    public int BlueValue
    {
        get { return _BlueValue; }
        set
        {
            if (_BlueValue != value)
            {
                _BlueValue = value;
                PropertyChanged(this, new PropertyChangedEventArgs("BlueValue"));
            }
        }
    }

    public SolidColorBrush GetColor()
    {
        Color res = new Color();
        res = Color.FromRgb(Convert.ToByte(RedValue), Convert.ToByte(GreenValue), Convert.ToByte(BlueValue));
        var result = new SolidColorBrush(res);
        return result;
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

我有一个将数据初始化到网格的加载方法。

    private void Load()
    {
        var colorList = _Context.ColorMix.ToList();
        foreach (var item in colorList)
        {
            var res = Color.FromRgb(Convert.ToByte(item.RedValue), Convert.ToByte(item.GreenValue), Convert.ToByte(item.BlueValue));
            var result = new SolidColorBrush(res);
            var dr = new DataGridRow();
            dr.Item = item;
            dr.Background = result;
            myColorGrid.Items.Add(dr);
        }
        dataGrid = myColorGrid;
    }

问题是该项目没有显示。只有颜色。 所以它变成了不同颜色的条纹。 我还需要显示该项目:P

【问题讨论】:

  • 您希望该项目看起来如何?

标签: c# wpf data-binding colors


【解决方案1】:

Brush 属性添加到您的ColorModel

public Brush Brush => GetColor();

DataGridItemsSource设置为colorList

private void Load()
{
    myColorGrid.ItemsSource = _Context.ColorMix.ToList();
    dataGrid = myColorGrid;
}

并使用ItemContainerStyle 将行的Background 属性绑定到ColorModelBrush 属性:

<DataGrid x:Name="myColorGrid">
    <DataGrid.ItemContainerStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="Background" Value="{Binding Brush}" />
        </Style>
    </DataGrid.ItemContainerStyle>
</DataGrid>

【讨论】:

  • 谢谢兄弟!欣赏它
猜你喜欢
  • 1970-01-01
  • 2012-04-20
  • 1970-01-01
  • 1970-01-01
  • 2012-12-23
  • 1970-01-01
  • 2013-10-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多