C# 在Wpf中更改DataGrid中行的颜色

C# 在Wpf中更改DataGrid中行的颜色,c#,wpf,xaml,datagrid,C#,Wpf,Xaml,Datagrid,我在更改DataGrid行的颜色时遇到问题,我使用以下函数 int i = 0; private void gvDados_LoadingRow(object sender, DataGridRowEventArgs e) { DataGridRow rowContext = e.Row; if (rowContext != null) { string Situacao = dt.Rows[i]["Situacao"].ToString(); if (

我在更改DataGrid行的颜色时遇到问题,我使用以下函数

int i = 0;
private void gvDados_LoadingRow(object sender, DataGridRowEventArgs e)
{
   DataGridRow rowContext = e.Row;
   if (rowContext != null)
   {
      string Situacao = dt.Rows[i]["Situacao"].ToString();
      if (Situacao.Equals("V"))
      {
         SolidColorBrush brush = new SolidColorBrush(Color.FromArgb(100, 255, 104,0));
         rowContext.Background = brush;
      }
      else
      {
         SolidColorBrush brush = new SolidColorBrush(Color.FromArgb(100, 255, 232,0));
         rowContext.Background = brush;
      }

      i++;
   }
}

到目前为止还不错,我可以根据需要调整颜色,问题是当我使用水平滚动条向下或向上移动寄存器时,所有颜色都被错误配置,随机出现。如何解决此问题,使滚动时不会发生变化?

每当“实例化”行时,
DataGrid
LoadingRow
事件就会触发。当您滚动行进入或退出范围时,会对“加载”到视图中的每一行重复触发此事件

假设您的
DataGrid
是在某个事件(如单击按钮或类似操作)中加载的,那么在实际将数据加载到
DataGrid
中时,您可能需要对行进行着色,最好使用为此编写的函数,稍后,如果内容发生更改并且您希望根据更改的内容显示颜色,请再次调用该函数

大概是这样的:

// This could be a button event, or some other event after which you load data into the DataGrid
void ButtonLoadEvent()
{
    foreach(Datagrid Row)
    {
        FunctionThatChangesRowColor(Row);
    }
}
编辑:

<Window x:Class="ColorLibrary.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ColorLibrary"
        mc:Ignorable="d"
        Loaded="Window_Loaded"
        Title="MainWindow" Height="500" Width="400">
    <Window.Resources>
        <Style TargetType="{x:Type DataGridRow}">
            <Style.Setters>
                <Setter Property="Background" Value="{Binding Path=Code}"></Setter>
            </Style.Setters>
        </Style>
    </Window.Resources>
    <Grid>

        <!-- Stuff -->

        <DataGrid Grid.Column="0" Grid.Row="2" Grid.ColumnSpan="2"
                  Name="dgvColors"
                  AutoGenerateColumns="False"
                  Margin="4">
            <DataGrid.Columns>
                <DataGridTemplateColumn Header="#" Width="Auto">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Num}" VerticalAlignment="Center" Padding="3"></TextBlock>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTemplateColumn Header="HTML Code" Width="Auto">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Code}" VerticalAlignment="Center" Padding="3"></TextBlock>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTemplateColumn Header="Color" Width="*">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Color}" VerticalAlignment="Center" Padding="3"></TextBlock>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>

    </Grid>
</Window>
关于如何获取DataGrid行和应用着色的实际代码。这是着色逻辑的一个修改版本,在这里,每一行根据其行索引是奇数还是偶数而着色。您可以将其替换为您的代码

将整个
DataGrid
传递到此函数

private void ColorRow(DataGrid dg)
{
    for (int i = 0; i < dg.Items.Count; i++)
    {
        DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(i);

        if (row != null)
        {
            int index = row.GetIndex();
            if (index % 2 == 0)
            {
                SolidColorBrush brush = new SolidColorBrush(Color.FromArgb(100, 255, 104, 0));
                row.Background = brush;
            }
            else
            {
                SolidColorBrush brush = new SolidColorBrush(Color.FromArgb(100, 255, 232, 0));
                row.Background = brush;
            }
        }
    }
}
private void ColorRow(数据网格dg)
{
对于(int i=0;i

但这也不是一个完美的解决方案,因为您使用的是WPF,而不是WinForms。我的一个建议是采用WPF数据绑定方法,让XAML为您进行颜色编码

是我经常用于此目的的代码示例

WPF进近代码:

<Window x:Class="ColorLibrary.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ColorLibrary"
        mc:Ignorable="d"
        Loaded="Window_Loaded"
        Title="MainWindow" Height="500" Width="400">
    <Window.Resources>
        <Style TargetType="{x:Type DataGridRow}">
            <Style.Setters>
                <Setter Property="Background" Value="{Binding Path=Code}"></Setter>
            </Style.Setters>
        </Style>
    </Window.Resources>
    <Grid>

        <!-- Stuff -->

        <DataGrid Grid.Column="0" Grid.Row="2" Grid.ColumnSpan="2"
                  Name="dgvColors"
                  AutoGenerateColumns="False"
                  Margin="4">
            <DataGrid.Columns>
                <DataGridTemplateColumn Header="#" Width="Auto">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Num}" VerticalAlignment="Center" Padding="3"></TextBlock>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTemplateColumn Header="HTML Code" Width="Auto">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Code}" VerticalAlignment="Center" Padding="3"></TextBlock>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTemplateColumn Header="Color" Width="*">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Color}" VerticalAlignment="Center" Padding="3"></TextBlock>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>

    </Grid>
</Window>

在,


code
是类中的属性,该类包含用于为单元格着色的颜色名称


然后我们有一个该类对象的
可观察集合。您需要将此属性(属于
ObservableCollection
中的每个项目)设置为您需要显示的每一行的颜色。

我需要以编程方式执行此操作如何读取数据网格中的每一行并更改其颜色?使用一段时间,并根据我的条件更改颜色,WPF方法是以编程方式进行的。您只需要让XAML进行着色,而不是在代码隐藏中进行着色。但是如果您必须使用代码隐藏,请参阅我发布的更新。在
DataGrid
行上使用
foreach
循环,并将行传递给为其着色的函数。使用foreach(gvData中的DataGridRow行){myfunction()}时发生错误,这只是伪代码。让我用一个例子更新一下如何获取每一行。@Sach,为什么属性值周围有双引号(比如
“500”
)?它不是有效的xaml,是吗?我很好奇,这是我第一次看到这样的标记