微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 使用foreach循环通过WPF DataGrid

所有,我试图循环通过 WPF DataGrid使用for each循环来改变错误单元格的背景颜色.我检查了很多问题,但我还没有找到足够的答案.到目前为止我所拥有的是什么
public void runchecks()
{
    const int baseColumnCount = 3;
    foreach (DaTarowView rv in dataGrid.Items)
    {
        for (int i = baseColumnCount; i < dataGrid.Columns.Count; i++)
        {
            if (!CheckForBalancedParentheses(rv.Row[i].ToString()))
            {
                Color color = (Color)ColorConverter.ConvertFromString("#FF0000");
                row.Background = new SolidColorBrush(color); // Problem!
            }
        }
    }
}

问题是,为了更改DataGrid中行的背景颜色,我需要使用与DaTarowView rv相关的DataGridRow对象.

如何从对象rv(DaTarowView)获取对DataGridRow的引用?

谢谢你的时间.

编辑.基于下面的建议,我现在有以下样式,它与鼠标悬停在事件上并设置相关单元格的后退和前导字体.但是,我真的迷失了如何在上面的代码中在运行时将backcolor应用到单元格. XML风格是

<Window.Resources>
    <Style targettype="{x:Type DataGridRow}">
        <Style.Triggers>
            <Trigger Property="IsMouSEOver"
                     Value="True">
                <Setter Property="Background" Value="Red" />
                <Setter Property="FontWeight" Value="ExtraBold" />
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

解决方法

在使用WPF时,请避免始终直接访问UI工件.

在ModelView中创建属性Color,并将其绑定到DataGrid视图的单行模板的背景颜色.

因此,为了更改颜色,您将循环抛出ModelView collecton并设置/读取绑定到每一行的每个对象的Color属性.通过更改它,如果正确设置了绑定,则会影响行UI颜色外观.

对于具体样品,您可以查看:

How do I bind the background of a data grid row to specific color?

原文地址:https://www.jb51.cc/csharp/239007.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐