循环遍历Silverlight DataGrid中的行

时间:2011-01-10 10:41:57

标签: c# .net silverlight silverlight-4.0

我有一种感觉,我在这里遗漏了一些明显的东西,但我无法找到迭代DataGrids DataGridRow集合的方法。我有一个网格,其中包含我的类集合的itemssource。我试图遍历行并突出显示符合某种条件的行,但不能在我的生活中看到如何。

2 个答案:

答案 0 :(得分:2)

您不想遍历网格。这是一个老式的WinForms思考。 WPF和Silverlight中的网格已经重新设计了MVVM;关注分离。您可以直接使用绑定到网格的对象,而不是操纵网格。所以网格只是一个演示问题。它的职责是根据这些对象中的数据读取对象并显示信息。

您要做的是将属性附加到您要绑定的对象,并根据这些设置设置颜色/字体/等的网格集样式。为此,您需要创建一个IValueConverter。

以下是我在WPF和Silverlight数据网格中的转换器示例:

public class StateToBackgroundColorConverter : IValueConverter
  {
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
      if (value == null) return Colors.White.ToString();

      var state = (State) value;
      return state.WebColor;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
      throw new NotImplementedException();
    }

    #endregion
  }

在我的XAML中,我声明如下:

<UserControl.Resources>
    <Converters:StateToBackgroundColorConverter x:Key="stateToBackgroundColorConverter"/>
</UserControl.Resources>

在XAML的datagrid声明中,我指定了DataGridRow的转换器用法:

 <toolkit:DataGrid.RowStyle>
          <Style TargetType="{x:Type toolkit:DataGridRow}">
            <Style.Setters>
              <Setter Property="FontWeight" Value="Bold" />
              <Setter Property="Foreground" Value="{Binding AgentState.SubState, Converter={StaticResource subStateToColorConverter}}" />
              <Setter Property="Background" Value="{Binding AgentState.State, Converter={StaticResource stateToBackgroundColorConverter}}" />
              <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
            </Style.Setters>
          </Style>
        </toolkit:DataGrid.RowStyle>

因此,转换器完成了工作。它读取State对象的值(它是我的AgentState对象上的子对象,它是网格绑定到的对象;它绑定到AgentState对象的集合)。转换器读取状态的值并返回用于为行设置的网格颜色的字符串表示形式。

希望有所帮助。

答案 1 :(得分:0)

您是否尝试过CollectionViewSource Class?

See Here

以及如何使用它进行过滤,请参阅下面的帖子

Filtering With CollectionViewSource