2012-12-17 54 views
8

如何让我的RowStyleAlternatingRowBackground之后得到应用?我希望IsOrangetrue的项目具有Orange背景,无论交替排列的行背景如何,目前情况并非如此。WPF DataGrid AlternatingRowBackground和RowStyle优先

XAML:

<DataGrid Name="g" 
    AlternatingRowBackground="Blue" 
    AlternationCount="2" 
    ... 
    SelectionMode="Single"> 
    <DataGrid.RowStyle> 
     <Style TargetType="DataGridRow"> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding IsOrange}" Value="Y"> 
        <Setter Property="Background" Value="Orange" /> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </DataGrid.RowStyle> 
    ... 
</DataGrid> 
+0

IsOrange属性位于哪里,它直接位于窗口上下文? – MoHaKa

+0

我有一个viewmodel SomethingWhichCanBeOrangeViewModel具有布尔IsRange属性。我的网格有它的ItemsSource设置为ObservableCollection 。 – user1514042

+0

好的,所以你确定你的财产可以在你的DataGrid中访问。 – MoHaKa

回答

12

这不是一个错误。在Style中,您无法覆盖为交替行设置的本地值。这就是为什么这是不行的

<DataGrid AlternatingRowBackground="Blue" 

但是,如果你在一个Style设置AlternatingRowBackground可以

<DataGrid.Style> 
    <Style TargetType="DataGrid"> 
     <Setter Property="AlternatingRowBackground" Value="Blue"/> 
    </Style> 
</DataGrid.Style> 

感谢this answer

+0

同意的种类,但是反过来说,交替行bg在样式之后被应用。 – user1514042

+0

谢谢!这正是我正在寻找的解决方案。 –

2

在我的程序中,除了包含一个DataGird的主窗口之外,我还有两个类。让我们先从第一类:

MyClass.cs:

public class MyClass 
{ 
    public bool IsOrange { get; set; } 

    public string Name { get; set; } 
} 

我只有两个属性,IsOrange指定该行是否应该橙色。 ((不关心其他属性))

现在视图模型类只包含MyClass的集合。

MyClassViewModel.cs:

public class MyClassViewModel 
{ 
    public ObservableCollection<MyClass> con { get; set; } 

    public MyClassViewModel() 
    { 
     con = new ObservableCollection<MyClass>(); 

     con.Add(new MyClass { IsOrange = true, Name = "Aa" }); 
     con.Add(new MyClass { IsOrange = true, Name = "Bb" }); 
     con.Add(new MyClass { IsOrange = false, Name = "Cc" }); 
     con.Add(new MyClass { IsOrange = false, Name = "Dd" }); 
     con.Add(new MyClass { IsOrange = false, Name = "Ee" }); 
     con.Add(new MyClass { IsOrange = true, Name = "Ff" }); 
     con.Add(new MyClass { IsOrange = true, Name = "Gg" }); 
     con.Add(new MyClass { IsOrange = false, Name = "Hh" }); 
    } 
} 

在MainWindow.xaml:

<Grid> 
    <DataGrid Margin="10" ItemsSource="{Binding Path=con}" > 
     <DataGrid.RowStyle> 
      <Style TargetType="DataGridRow"> 
       <Style.Triggers> 
        <DataTrigger Binding="{Binding Path=IsOrange}" Value="true"> 
         <Setter Property="Background" Value="Orange" /> 
        </DataTrigger> 
       </Style.Triggers> 
      </Style> 
     </DataGrid.RowStyle> 
    </DataGrid> 
</Grid> 

终于在MainWindow.xaml.cs:

public partial class MainWindow : Window 
{ 
    MyClassViewModel VM = new MyClassViewModel(); 

    public MainWindow() 
    { 
     InitializeComponent(); 

     DataContext = VM; 
    } 
} 

,这是结果:

enter image description here

你可以给我您的电子邮件发送给您的应用程序。

好运:)