c# - WPF DataGrid动态列数,DataCell背景颜色根据值变化
问题描述
我创建了一个DataGrid
我想定期更新的内容,并且我希望背景根据字节值进行更改。我还希望用户能够在运行时更改列数。
<DataGrid x:Name="IODataGrid" ItemsSource="{Binding}" AutoGenerateColumns="true" IsReadOnly="True" HeadersVisibility="None" ColumnWidth="*"></DataGrid>
在 c# 代码中,我尝试DataGrid
用DataRow
s 和DataGridCell
s 填充,但我无法让网格正确显示。
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++ - 为什么在 Qt 中创建主窗口之前必须加载语言包?
- session - 关于自由的 ViewExpiredException
- java - ArrayList 打印位置而不是输入值
- java - 解析 JSON 以映射到数组
- c# - Telerik Form 作为对话框运行有时会卡住
- java - 错误 404:无法在 JSP 中加载 css 页面
- javascript - 使用 ECMAScript 解构访问对象中的所有元素
- php - PHP + 生成 .html 文件供下载
- vba - VBA从一个excel表复制到另一个excel表?
- playframework-2.6 - 为什么我没有看到任何访问控制标头