您不想遍历网格。这是老式的 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 的数据网格声明中,我指定了 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 对象的集合)。转换器读取状态值并返回颜色的字符串表示形式,供网格用于设置行。
希望有帮助。