0

我想制作包含 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。

4

1 回答 1

2

最好的方法是使用DataTrigger的样式,DataGridItemsbool?在绑定到DataTrigger. 在DataTrigger你可以声明所有三个状态的视觉Null, True, False

有关更多信息DataTrigger,请查看此处

编辑

嗯,有没有机会将突出显示功能放在DataTemplate? 我为实体的选择状态实现了突出显示。它按预期工作。

<DataTemplate.Triggers>
  <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=ListBoxItem}}"
                  Value="true">
  <!-- Expand -->
  <DataTrigger.EnterActions>
    <BeginStoryboard>
      <Storyboard Storyboard.TargetName="CommandPanel">
        <DoubleAnimation Duration="0:0:0.200" Storyboard.TargetProperty="Opacity" To="1" />
        <DoubleAnimation Duration="0:0:0.150" Storyboard.TargetProperty="Height"
                            To="{StaticResource TargetHeightCommandPanel}" />
      </Storyboard>
    </BeginStoryboard>
  </DataTrigger.EnterActions>
  <!-- Collapse -->
  <DataTrigger.ExitActions>
      <BeginStoryboard>
        <Storyboard Storyboard.TargetName="CommandPanel">
          <DoubleAnimation Duration="0:0:0.100" Storyboard.TargetProperty="Opacity" To="0" />
          <DoubleAnimation Duration="0:0:0.150" Storyboard.TargetProperty="Height" To="0" />
        </Storyboard>
      </BeginStoryboard>
    </DataTrigger.ExitActions>
  </DataTrigger>
</DataTemplate.Triggers>

顺便说一句,你听说过 MVVM 吗?

于 2012-12-10T16:51:02.063 回答