简体   繁体   English

C#WPF datagrid行背景色

[英]C# WPF datagrid row background color

I have the below simplified code to color certain rows of my DataGrid. 我有以下简化的代码为DataGrid的某些行着色。 I would like to do this task programmatically and not through XAML. 我想以编程方式而不是通过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. 这样做不会更改行的背景。

This won't work unless you display very few rows in your DataGrid or 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 DataGrid in WPF is to define a RowStyle , preferably in XAML: 在WPF中更改DataGrid中行的背景颜色的正确方法是定义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. 尝试仅按原样“转换” Windows Forms代码肯定是错误的方法。 WPF and Windows Forms are two different frameworks/technologies and you don't do things the same way in both. WPF和Windows窗体是两个不同的框架/技术,您在这两者中做事并不相同。 Then it would be pretty much useless to convert in the first place. 那么首先转换几乎没有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM