C# WPF 数据网格行背景色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45858033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# WPF datagrid row background color
提问by nerdalert
I have the below simplified code to color certain rows of my DataGrid. I would like to do this task programmatically and not through XAML.
我有下面的简化代码来为我的 DataGrid 的某些行着色。我想以编程方式而不是通过 XAML 来完成此任务。
public IEnumerable<System.Windows.Controls.DataGridRow> GetDataGridRows(System.Windows.Controls.DataGrid grid)
{
var itemsSource = grid.ItemsSource as IEnumerable;
if (null == itemsSource) yield return null;
foreach (var item in itemsSource)
{
var row = grid.ItemContainerGenerator.ContainerFromItem(item) as System.Windows.Controls.DataGridRow;
if (null != row) yield return row;
}
}
public void color()
{
var rows = GetDataGridRows(dg1);
foreach (DataGridRow r in rows)
{
//DataRowView rv = (DataRowView)r.Item;
//remove code for simplicity
r.Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(100, 100, 100, 100));
}
}
Doing this does not change the background of the row.
这样做不会改变行的背景。
回答by mm8
This won't work unless you display very few rows in your DataGridor disable the UI virtualization (which of course may lead to performance issues).
这将不起作用,除非您显示很少的行DataGrid或禁用 UI 虚拟化(这当然可能导致性能问题)。
The correct way do change the background colour of the rows in a DataGridin WPF is to define a RowStyle, preferably in XAML:
DataGrid在 WPF 中更改 a中行的背景颜色的正确方法是定义 a RowStyle,最好在 XAML 中:
<DataGrid x:Name="grid">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="Background" Value="#64646464" />
</Style>
</DataGrid.RowStyle>
</DataGrid>
Trying to just "convert" your Windows Forms code as-is is certainly a wrong approach. WPF and Windows Forms are two different frameworks/technologies and you don't do things the same way in both. Then it would be pretty much useless to convert in the first place.
试图按原样“转换”您的 Windows 窗体代码肯定是一种错误的方法。WPF 和 Windows 窗体是两种不同的框架/技术,您在两者中的处理方式不同。那么一开始就转换几乎没用。

