首页 > 解决方案 > WPF DataGrid动态列数,DataCell背景颜色根据值变化

问题描述

我创建了一个DataGrid我想定期更新的内容,并且我希望背景根据字节值进行更改。我还希望用户能够在运行时更改列数。

<DataGrid x:Name="IODataGrid" ItemsSource="{Binding}" AutoGenerateColumns="true" IsReadOnly="True" HeadersVisibility="None" ColumnWidth="*"></DataGrid>

在 c# 代码中,我尝试DataGridDataRows 和DataGridCells 填充,但我无法让网格正确显示。

public partial class IOMonitor : Grid, INotifyPropertyChanged
{
    public DataTable _ioTable = new DataTable();
    private List<IO> _ioLst = new List<IO>();
    private Timer updateTimer = new Timer();
    public int maxIOPerLine = 8;
    public IOMonitor()
    {
        InitializeComponent();
        IODataGrid.DataContext = _ioTable.DefaultView;
        for (int i = 0; i < maxIOPerLine; i++)
        {
            _ioTable.Columns.Add(i.ToString());
        }
        updateTimer = new System.Timers.Timer(1000);
        updateTimer.Elapsed += checkIO;
    }
    private void checkIO(object sender, EventArgs e)
    {
        List<IO> io = getIO();
        if (io == null)
            return; 
        _ioLst = io;
        Dispatcher.BeginInvoke((Action)delegate()
        {
            _ioTable.Rows.Clear();
            List<List<IO>> tmpLst = new List<List<MoniterIO>>();
            for (int i = 0; i < _ioLst.Count; i += maxIOPerLine)
            {
                tmpLst.Add(_ioLst.GetRange(i, Math.Min(maxIOPerLine, _ioLst.Count - i)));
            }
            foreach (List<IO> ioLine in tmpLst)
            {
                DataRow row = _ioTable.NewRow();
                for (int i = 0; i < maxIOPerLine; i++)
                {
                    DataGridCell cell = new DataGridCell();
                    cell.Content = ioLine[i].text;
                    if (ioLine[i].data == 1)
                        cell.Background = Brushes.LightGreen;
                    row[i.ToString()] = cell;
                }
                _ioTable.Rows.Add(row);
            }
        });
    }
    public event PropertyChangedEventHandler PropertyChanged;
    public void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

网格中的每个单元格都显示单词System.Controls.DataGridCell: desired_string并且无法更改背景颜色。我尝试使用 aTextBlock而不是,DataGridCell我遇到了同样的问题。如果我尝试这个,我可以让文本正确显示:

DataRow row = _ioTable.NewRow();
for (int i = 0; i < maxIOPerLine; i++)
{
    row[i.ToString()] = cell;
}
_ioTable.Rows.Add(row);

但我无法根据需要更改背景颜色。我不想硬编码 WPF 中的列,因为列数可能会改变。

标签: c#wpfxamldynamicdatagrid

解决方案


推荐阅读