[英]C# WPF datagrid row background color
我有以下简化的代码为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));
}
}
这样做不会更改行的背景。
除非您在DataGrid
显示很少的行或禁用UI虚拟化(否则可能会导致性能问题),否则它将无法正常工作。
在WPF中更改DataGrid
中行的背景颜色的正确方法是定义RowStyle
,最好在XAML中:
<DataGrid x:Name="grid">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="Background" Value="#64646464" />
</Style>
</DataGrid.RowStyle>
</DataGrid>
尝试仅按原样“转换” Windows Forms代码肯定是错误的方法。 WPF和Windows窗体是两个不同的框架/技术,您在这两者中做事并不相同。 那么首先转换几乎没有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.