着色WPF DataGridRows一个一个 [英] Coloring WPF DataGridRows one by one

查看:193
本文介绍了着色WPF DataGridRows一个一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个WPF程序,它能够在 DataGrid 中以红色逐行使用循环,我遇到了一些奇怪的东西。如果 DataGrid 从数据库表中有40行以上的数据,它不会对所有行进行着色。

I'm making a WPF program which is able to color the rows in a DataGrid one by one in red using the for loop and I've encountered something weird. If the DataGrid has more than 40 rows of data from a database table, it doesn't color all the rows.

这里是我使用的代码。

private void Red_Click(object sender, RoutedEventArgs e)
{
    for (int i = 0; i < dataGrid1.Items.Count; i++)
    {
        DataGridRow row = (DataGridRow)dataGrid1.ItemContainerGenerator.ContainerFromIndex(i);
        if (row != null)
        {
            row.Background = Brushes.Red;
        }
    }
}

推荐答案

如果你想定义颜色对于每一行,你有一个属性的项目的行显示你可以使用ItemsContainerStyle设置行颜色。在下面的示例中,您将在网格中的项目上有一个名为ItemColour的属性,它将定义背景行颜色。绑定从行到该行包含的项目。

If you want to define colours for each row and you have a property on the items the rows display you can use an ItemsContainerStyle to set the row colour. In the example below you would have a property called ItemColour on your items in the grid which would define the background row colour. The binding binds from the row to the item the row contains.

 <dg:DataGrid.ItemContainerStyle>
    <Style
       TargetType="{x:Type dg:DataGridRow}"
       BasedOn="{StaticResource {x:Type dg:DataGridRow}}">
       <Setter
          Property="Background"
          Value="{Binding ItemColour}" />
    </Style>
 </dg:DataGrid.ItemContainerStyle>

但是您可能不希望项目上有ItemColour属性,因为它们可能是您的业务模型。这是一个ViewModel进入自己的。您可以基于一些自定义逻辑定义包装业务层的中间层和ItemColour属性。

But you might not want a property ItemColour on your items as they might be your business model. This is where a ViewModel comes into its own. you define a middle layer that wraps your business layer and the ItemColour property based on some custom logic.

这篇关于着色WPF DataGridRows一个一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆