简体   繁体   English

WPF DataGrid 从后面的代码覆盖单行的选择颜色

[英]WPF DataGrid override the selection color of a single row from code behind

I'm trying to change the color of a single row in a DataGrid from the code behind, even if the row is selected and therefore already changed color.我正在尝试从后面的代码更改DataGrid单行的颜色,即使该行已被选中并因此已更改颜色。

If the row is not selected I can just use:如果未选择该行,我可以使用:

((DataGridRow)row).Background = Brushes.Orange;

This works fine, but when the row is selected the orange color doesn't show over the blue selection color.这有效,但选择行时,橙色不会显示在蓝色选择颜色上。 How can I set a color to show over the selection for a single row (not the whole DataGrid ).如何设置颜色以显示在单行(而不是整个DataGrid )的选择上。

You need to set the Background of the cells:您需要设置单元格的Background

private void SomeMethod()
{
    var row = ...;

    foreach (DataGridCell cell in FindVisualChildren<DataGridCell>(row))
        cell.Background = Brushes.Orange;
}

private static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj != null)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
            if (child != null && child is T)
                yield return (T)child;

            foreach (T childOfChild in FindVisualChildren<T>(child))
                yield return childOfChild;
        }
    }
}

Having said that, you should still prefer to define custom styles in XAML instead of modifying properties of visual containers programmatically.话虽如此,您仍然应该更喜欢在 XAML 中定义自定义样式,而不是以编程方式修改可视容器的属性。

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

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