WPF Datagrid单元格着色

zu0ti5jz  于 2023-11-21  发布在  其他
关注(0)|答案(3)|浏览(194)

我们如何在WPF数据网格中以编程方式为单元格添加颜色?我可以为行添加颜色,但我想从后面的代码为单元格添加颜色。请提供代码?

drnojrws

drnojrws1#

这段代码的作用:首先,处理LoadingRow事件,获取行(它具有保存绑定项的Item属性),获取绑定项,进行所有需要的计算,获取需要更改的单元格,最后更改目标单元格的样式。
下面是代码(作为项目,我使用了一个带有int ID属性的示例对象,用于着色)。

C#:

private void FillTheDataGrid()
{
    List<SomeClass> list = new List<SomeClass>();
    Random rnd = new Random();
    for (int i = 0; i < 10; i++)
    {        
       list.Add(new SomeClass() { DaysOld = DateTime.Now.Add(new TimeSpan(rnd.Next(5), 0, 0, 0)), ID=i});
     }
     dataGrid.ItemsSource = list;
}

private void dataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
    Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(() => AlterRow(e)));
}

private void AlterRow(DataGridRowEventArgs e)
{
    var cell = GetCell(dataGrid, e.Row, 1);
    if (cell == null) return;

    var item = e.Row.Item as SomeClass;
    if (item == null) return;

    var value = item.ID;

    if (value <= 1) cell.Background = Brushes.Red;
    else if (value <= 2) cell.Background = Brushes.Yellow;
    else cell.Background = Brushes.Green;
}

public static DataGridRow GetRow(DataGrid grid, int index)
{
    var row = grid.ItemContainerGenerator.ContainerFromIndex(index) as DataGridRow;

    if (row == null)
    {
        // may be virtualized, bring into view and try again
        grid.ScrollIntoView(grid.Items[index]);
        row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
    }
    return row;
}

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++)
    {
        var v = (Visual)VisualTreeHelper.GetChild(parent, i);
        child = v as T ?? GetVisualChild<T>(v);
        if (child != null)
        {
            break;
        }
    }
    return child;
}

public static DataGridCell GetCell(DataGrid host, DataGridRow row, int columnIndex)
{
    if (row == null) return null;

    var presenter = GetVisualChild<DataGridCellsPresenter>(row);
    if (presenter == null) return null;

    // try to get the cell but it may possibly be virtualized
    var cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
    if (cell == null)
    {
        // now try to bring into view and retreive the cell
        host.ScrollIntoView(row, host.Columns[columnIndex]);
        cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
    }
    return cell;
}

字符串

型号:

public class SomeClass
{
    public int ID { get; set; }
    public DateTime DaysOld { get; set; }
}

XAML:

<DataGrid Name="dataGrid" AutoGenerateColumns="True" LoadingRow="dataGrid_LoadingRow"/>

mm5n2pyu

mm5n2pyu2#

我也遇到了同样的问题,最后我找到了答案,它比我想的要容易,下面是代码来改变单元格的颜色:

DataGridRow firstRow = dataGrid.ItemContainerGenerator.ContainerFromItem(dataGrid.Items[i]) as DataGridRow; 
firstColumnInFirstRow = dataGrid.Columns[j].GetCellContent(firstRow).Parent as DataGridCell;
firstColumnInFirstRow.Background = Brushes.IndianRed;

字符串

nwnhqdif

nwnhqdif3#

根据DataGridCell中的内容,您可以创建绑定到颜色或使用触发器的DataTemplate

<DataTemplate DataType="{x:Type cell:MyCellObject}"> 
    <TextBlock TextAlignment="Center" Text="{Binding Text}">
        <TextBlock.Style>
            <Style TargetType="TextBlock">
                <Setter Property="Background" Value="{Binding MyBackground}" />
                <Setter Property="Foreground" Value="Black" />
                <Setter Property="Padding" Value="0" />

                <Style.Triggers>    
                    <DataTrigger Binding="{Binding MyBool}" Value="True">
                        <Setter Property="Foreground" Value="DarkRed" />
                        <Setter Property="FontWeight" Value="Bold" />
                    </DataTrigger>
                </Style.Triggers>

           </Style>
        </TextBlock.Style>
    </TextBlock>
</DataTemplate>

字符串

相关问题