简体   繁体   English

如何根据绑定属性设置 WPF 数据网格的样式

[英]How to style WPF datagrid based on binded property

I have been stuck in the DataGrid styling for hours.我被困在 DataGrid 样式中已经好几个小时了。 I have searched many solutions but to no avail, I haven't been able to apply the styling on my design.我搜索了许多解决方案,但无济于事,我无法将样式应用于我的设计。

I have this in my View.xaml:我的 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>

What I want to accomplish in this code is that when the ColorStyle value changes, the data row background color also changes depending on what was specified on the DataTrigger but this doesn't seem to work.我想在这段代码中完成的是,当 ColorStyle 值发生变化时,数据行背景颜色也会根据 DataTrigger 上指定的内容而变化,但这似乎不起作用。 I do not know what part of my code I should change.我不知道我应该更改代码的哪一部分。

//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>

if correctly understood your code, then GridRow context does not see ColorStyle, because it is not in the TransactionList, but in the same place as the ItemsSource.如果正确理解您的代码,则 GridRow 上下文不会看到 ColorStyle,因为它不在 TransactionList 中,而是与 ItemsSource 位于同一位置。 You need to do你需要做

<DataTrigger Binding = "{Binding RelativeSource = {RelativeSource Mode = FindAncestor, AncestorType = DataGrid}, Path = DataContext.ColorStyle}" Value = "Green">

or transfer ColorStyle to class TransactionList或将 ColorStyle 转移到 class TransactionList

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM