[英]How to style WPF datagrid based on binded property
我被困在 DataGrid 样式中已经好几个小时了。 我搜索了许多解决方案,但无济于事,我无法将样式应用于我的设计。
我的 View.xaml 中有这个:
<DataGrid x:Name="dgTransactions"
CanUserAddRows="False"
ColumnHeaderStyle="{StaticResource HeaderStyle}"
ItemsSource="{Binding TransactionLists, Mode=TwoWay}">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding ColorStyle}" Value="Red">
<Setter Property="Background" Value="Red"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding ColorStyle}" Value="Blue">
<Setter Property="Background" Value="Blue"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding ColorStyle}" Value="Green">
<Setter Property="Background" Value="Green"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
</DataGrid>
我想在这段代码中完成的是,当 ColorStyle 值发生变化时,数据行背景颜色也会根据 DataTrigger 上指定的内容而变化,但这似乎不起作用。 我不知道我应该更改代码的哪一部分。
//may it help don't need to code in .cs just in .xaml
//just add your properties in binding let me know if any error
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding _age}" Value="20">
<Setter Property="Background" Value="Red"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding _ismale}" Value="true">
<Setter Property="Background" Value="Green"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
如果正确理解您的代码,则 GridRow 上下文不会看到 ColorStyle,因为它不在 TransactionList 中,而是与 ItemsSource 位于同一位置。 你需要做
<DataTrigger Binding = "{Binding RelativeSource = {RelativeSource Mode = FindAncestor, AncestorType = DataGrid}, Path = DataContext.ColorStyle}" Value = "Green">
或将 ColorStyle 转移到 class TransactionList
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.