我想制作包含 DataGrid 控件并在 C# WPF DataGrid 中启用以下场景的 WPF 窗口:在 DataGrid 中加载数据,应用程序在后台验证数据(并行异步操作),当确定行有效时,其背景颜色变为绿色,否则为红色。对这种行为进行编程的最干净的方法是什么?DataGrid 和 WPF 中是否有任何内置功能可以进行这种验证?
编辑:现在我已经设法通过使用 RowStyle 来执行此操作,但这会使应用程序无响应,因为验证每一行都需要时间,所以我想让这个异步和并行。
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="Background" Value="{Binding BgColor}">
</Setter>
</Style>
</DataGrid.RowStyle>
EDIT2:这是进展:
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=BgColor}" Value="DarkRed">
<Setter Property="Background" Value="DarkRed"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
后面的代码如下所示:
Func<List<bool>> func = () => data.AsParallel().Select(x => File.Exists(x.FullPath)).ToList();
List<bool> res = null;
IAsyncResult ar = func.BeginInvoke(new AsyncCallback(x=>
{
res = ((Func<List<bool>>)((AsyncResult)x).AsyncDelegate).EndInvoke(x);
for (int i = 0; i < res.Count; ++i)
if (!res[i])
data[i].BgColor = Brushes.DarkRed;
}), null);
剩下的问题是只有在重绘行时才会刷新行背景颜色(移出视图而不是再次进入视图)。有什么干净简单的方法来解决这个问题吗?
EDIT3:最后一切都完全按要求工作,EDIT2 中唯一缺少的是在数据源类中实现 INotifyPropertyChanged。