【问题标题】:Change colour of datagrid row cell更改数据网格行单元格的颜色
【发布时间】:2013-12-18 12:40:53
【问题描述】:

我有一个通过将其绑定到数据表来填充的数据网格。

有 100 行。

使用 c# 如何更改特定单元格的背景颜色?

比如说第 15 行,我想要的背景颜色是绿色。

数据网格

<DataGrid Name="grid" ItemsSource="{Binding}" Height="300" Width="900"
          AutoGenerateColumns="True"
          VerticalScrollBarVisibility="Disabled" HorizontalAlignment="Center" VerticalAlignment="Top" RowHeight="40">
            <DataGrid.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel Orientation="Vertical" />
                </ItemsPanelTemplate>
            </DataGrid.ItemsPanel>
        </DataGrid>

【问题讨论】:

  • 删除那些可怕的无类型、基于魔法字符串的 DataTable 东西,并为此创建一个适当的、强类型的 ViewModel。然后只需使用Style.Triggers 或类似方法根据来自基础数据的值更改单元格背景。不要在 WPF 的过程代码中操作 UI 元素。这就是 XAML 的用途。

标签: c# wpf datagrid


【解决方案1】:

实际上,没有任何方法可以访问 WPF Datagrid 中的单个行,你不应该这样做! 更好的方法是使用样式设置器

<Style TargetType="{x:Type DataGridCell}" x:Key="NumberCell">      
<Style.Setters>
    <Setter Property="Background" Value="{Binding backgroundColor></Setter>
</Style.Setters>

除非您不能这样做,否则还有其他选择: 我前段时间在网上找到了这个解决方案,但不记得在哪里。

首先我们需要一些辅助函数。只需添加此类

namespace YOURNAMESPACE.DataGridHelpers
/// <summary>
/// Extension methods for DataGrid
/// </summary>
public static class DataGridHelper
{
    /// <summary>
    /// Gets the visual child of an element
    /// </summary>
    /// <typeparam name="T">Expected type</typeparam>
    /// <param name="parent">The parent of the expected element</param>
    /// <returns>A visual child</returns>
    public static T GetVisualChild<T>(Visual parent) where T : Visual
    {
        T child = default(T);
        int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < numVisuals; i++)
        {
            Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
            child = v as T;
            if (child == null)
            {
                child = GetVisualChild<T>(v);
            }
            if (child != null)
            {
                break;
            }
        }
        return child;
    }



    /// <summary>
    /// Gets the specified cell of the DataGrid
    /// </summary>
    /// <param name="grid">The DataGrid instance</param>
    /// <param name="row">The row of the cell</param>
    /// <param name="column">The column index of the cell</param>
    /// <returns>A cell of the DataGrid</returns>
    public static DataGridCell GetCell(this DataGrid grid, DataGridRow row, int column)
    {
        if (row != null)
        {
            DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);

            if (presenter == null)
            {
                grid.ScrollIntoView(row, grid.Columns[column]);
                presenter = GetVisualChild<DataGridCellsPresenter>(row);
            }

            DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);

            return cell;
        }
        return null;
    }

    /// <summary>
    /// Gets the specified cell of the DataGrid
    /// </summary>
    /// <param name="grid">The DataGrid instance</param>
    /// <param name="row">The row index of the cell</param>
    /// <param name="column">The column index of the cell</param>
    /// <returns>A cell of the DataGrid</returns>
    public static DataGridCell GetCell(this DataGrid grid, int row, int column)
    {
        DataGridRow rowContainer = grid.GetRow(row);
        return grid.GetCell(rowContainer, column);
    }

    /// <summary>
    /// Gets the specified row of the DataGrid
    /// </summary>
    /// <param name="grid">The DataGrid instance</param>
    /// <param name="index">The index of the row</param>
    /// <returns>A row of the DataGrid</returns>
    public static DataGridRow GetRow(this DataGrid grid, int index)
    {
        DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
        if (row == null)
        {
            // May be virtualized, bring into view and try again.
            grid.UpdateLayout();
            grid.ScrollIntoView(grid.Items[index]);
            row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
        }
        return row;
    }

    /// <summary>
    /// Gets the selected row of the DataGrid
    /// </summary>
    /// <param name="grid">The DataGrid instance</param>
    /// <returns></returns>
    public static DataGridRow GetSelectedRow(this DataGrid grid)
    {
        return (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem);
    }
}

}

现在您可以通过以下方式获取 DataGrid Column 0 row 15:

var cell = dataGrid.GetCell( 15, 0);

并将颜色设置为绿色

cell.Background = Brushes.Green;

【讨论】:

    【解决方案2】:

    像这样向DataGridLoadingRow 事件添加处理程序:

        <DataGrid Name="grid" ItemsSource="{Binding}" Height="300" Width="900"
                AutoGenerateColumns="True" VerticalAlignment="Top" RowHeight="40"
                VerticalScrollBarVisibility="Disabled" HorizontalAlignment="Center"  
                LoadingRow="DataGrid_LoadingRow" >
            <DataGrid.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel Orientation="Vertical" />
                </ItemsPanelTemplate>
            </DataGrid.ItemsPanel>
        </DataGrid>
    

    然后在后面的代码中:

         int index = 0;
         public void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
         {
            var row = (DataRowView)e.Row.Item;
            //If you want the content of a specific column of the current row
            //var content = row.Row[0].ToString(); 
            if (index == 15)
            {
                e.Row.Background = new SolidColorBrush(Colors.DeepSkyBlue);
                e.Row.Foreground = new SolidColorBrush(Colors.Black);
            }
            index ++ ; //don't forget to increase the index
         }
    

    【讨论】:

    • 我明白了:无法在 var row = (DataRowView)e.Row.Item 上将“MS.Internal.NamedObject”类型的对象转换为“System.Data.DataRowView”;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 2019-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    相关资源
    最近更新 更多