gpt4 book ai didi

c# - WPF根据条件以编程方式更改行背景颜色

转载 作者:行者123 更新时间:2023-12-03 22:48:58 25 4
gpt4 key购买 nike

我正在尝试使用 LoadingRow 以编程方式更改行颜色。它正在按我的需要工作。但是问题出在滚动条上。当我在数据网格中使用滚动条时,我的公式再次运行并且我得到了愚蠢的有序行颜色。

这是我的代码。我正在尝试使用第 17 列值更改颜色。

        private void dataGrid1_LoadingRow(object sender, DataGridRowEventArgs e)
{
DataGridRow row = e.Row;
DataRowView rView = row.Item as DataRowView;
if (rView != null && rView.Row.ItemArray[17].ToString().Contains("1"))
{
renk++;
}
if (renk % 2 == 0)
{
e.Row.Background = (SolidColorBrush)(new BrushConverter().ConvertFrom("#FF0000"));
}
else
{
e.Row.Background = (SolidColorBrush)(new BrushConverter().ConvertFrom("#ffffff"));
}
}

运行我的代码后,它就可以工作了。但是,当我向下滚动鼠标以查看以下行时,它也可以正常工作。然后,当我向上滚动鼠标以查看第一行时,我的代码无法正常工作。您可以看到打开时间和滚动下面图片后的区别。

First order is good Why it is confusing

谢谢。

最佳答案

如果您在 DataGrid 上关闭虚拟化,这应该可以工作:

<DataGrid
EnableRowVirtualization="False"

它为不同的行重用 DataGridRow 对象。如果您有 10,000 行并且其中 30 行是可见的,那么创建 10,000 个 DataGridRow 控件对象是愚蠢的。如果您有足够的项目,以上内容将使您的应用程序陷入困境。但是,您的元素数量可能很少,在这种情况下,上面的拼凑就足够了。

但在任何情况下您都不需要这样做。正确的方法是启用行虚拟化并使用 WPF 而不是反对它,如下面的 XAML。

我不知道您的第 17 列叫什么,所以我创建了一个快速表,其中填充了 fizz buzz 项目。我的第 17 列相当于一个名为 State 的列。如果您提供更多信息,我们可以使它与您的实际操作相匹配。

<DataGrid
ItemsSource="{Binding FizzBuzzTable}"
>
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding State}" Value="Fizz">
<Setter Property="Background" Value="LightYellow" />
</DataTrigger>
<DataTrigger Binding="{Binding State}" Value="Buzz">
<Setter Property="Background" Value="LightSkyBlue" />
</DataTrigger>
<DataTrigger Binding="{Binding State}" Value="FizzBuzz">
<Setter Property="Background" Value="GreenYellow" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
</DataGrid>

关于c# - WPF根据条件以编程方式更改行背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42906575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com