【发布时间】:2012-12-10 16:43:43
【问题描述】:
我想制作包含 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>
编辑2: 这是进展:
<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);
剩下的问题是,只有在重绘行时才会刷新行背景颜色(移出视图而不是再次进入视图)。有什么干净简单的方法可以解决这个问题吗?
编辑3: 最后一切都完全按要求工作,EDIT2 中唯一缺少的是在数据源类中实现 INotifyPropertyChanged。
【问题讨论】:
-
您可能希望在其中添加一些 XAML 代码,以便我们更好地了解您目前所拥有的内容。
标签: c# wpf wpf-controls wpfdatagrid