2013-10-15 36 views
0

我將DataGrid綁定到模型並希望根據數據更改行的顏色。例如,如果模型屬性錯誤是真的。這是我目前有:如何爲MVVM Light應用程序中的DataGrid行着色代碼

<Grid Name="MyGrid"> 
    <DataGrid ItemsSource="{Binding Path=MyData}"> 
     <DataGrid.RowStyle> 
      <Style TargetType="DataGridRow">      
       <Style.Triggers> 
        <Trigger Property="{Binding Path=Error}" Value="true"> 
         <Setter Property="Background" Value="Red"/> 
        </Trigger> 
       </Style.Triggers> 
      </Style> 
     </DataGrid.RowStyle> 
     <DataGrid.Columns> 
      <DataGridTextColumn Header="Field1" Binding="{Binding Field1}"/> 
      <DataGridTextColumn Header="Field2" Binding="{Binding Field2}"/> 
      <DataGridTextColumn Header="Field3" Binding="{Binding Field3}"/> 
      <DataGridTextColumn Header="Field4" Binding="{Binding Field4}"/> 
     </DataGrid.Columns> 
    </DataGrid> 

這種做法給我的編譯時錯誤:

A 'Binding' cannot be set on the 'Property' property of type 'Trigger'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject. 
+0

這是什麼[StyleSelectors](http://msdn.microsoft.com/en-us/library/system.windows.controls .styleselector.aspx) –

回答

3

您可以使用RowStyleSelector爲:

public class MyStyleSelector : StyleSelector 
{ 
    public Style RegularStyle { get; set; } 

    public Style ErrorStyle { get; set; } 

    public override Style SelectStyle(object item, System.Windows.DependencyObject container) 
    { 
     var model = item as YourModel; 

     // Avoid possible NullReferenceException 
     if (model is null) return RegularStyle; 

     // Here you determine which style to use based on the property in your model 
     if (model.Error) 
     { 
      return ErrorStyle; 
     } 

     return RegularStyle; 
    } 
} 

然後創建它作爲一個資源您的xaml並定義您的款式

 <local:MyStyleSelector x:Key="rowStyleSelector"> 
      <local:MyStyleSelector.RegularStyle> 
       <Style TargetType="DataGridRow"> 
        <Setter Property="Background" Value="White"/> 
       </Style> 
      </local:MyStyleSelector.RegularStyle> 
      <local:MyStyleSelector.ErrorStyle> 
       <Style TargetType="DataGridRow"> 
        <Setter Property="Background" Value="Red"/> 
       </Style> 
      </local:MyStyleSelector.ErrorStyle> 
     </local:MyStyleSelector> 

而且用它在你的網格:

<DataGrid ItemsSource="{Binding SomeCollection}" RowStyleSelector="{StaticResource rowStyleSelector}"> 

希望這有助於

相關問題