2011-01-10 104 views
3

我有一種感覺,我在這裏忽略了一些明顯的東西,但我找不到通過DataGrids DataGridRow集合進行迭代的方式。我有一個網格,它有我的課程集合的一個itemSource。我試圖遍歷行並突出顯示任何滿足特定條件的行,但不能爲我的生活看到如何。循環遍歷Silverlight DataGrid中的行

回答

2

你不想通過網格進行迭代。這是老式的WinForms思維。 WPF和Silverlight中的網格已經根據MVVM進行了重新設計;關注點分離。您不用操縱網格,而直接使用綁定到網格的對象。所以網格只是一個演示問題。它的責任是讀取對象並根據這些對象中的數據顯示信息。

你想要做的是將屬性附加到綁定到的對象上,並根據這些設置爲顏色/字體/等設置網格設置樣式。要做到這一點,你需要創建一個IValueConverter。

這裏是一個轉換器我有一個WPF和Silverlight的DataGrid的例子:

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對象)。轉換器讀取狀態的值並返回網格用於爲該行設置的顏色的字符串表示形式。

希望有所幫助。