首页 > 解决方案 > 根据其他单元格值的值更改 WPF Gridcell 的单元格格式

问题描述

我开始涉足 WPF MVVM。现在在网格中,我需要根据另一个单元格中的值来格式化单元格的外观。

当前网格示例1

“SAP No.”中的值 如果视图模型中的值“DoppelSAPOrder”为真,则应显示为红色。值“DoppelSAPOrder”未显示在网格中。

网格位于 UserControl 上

<UserControl...

    <UserControl.DataContext>
    <model:MainVM />
</UserControl.DataContext>

<Grid>
    <datagrid:ThemedDataGrid HorizontalAlignment="Stretch" Height="auto" VerticalAlignment="Stretch" Width="auto"
                             x:Name="DataGrid" ItemsSource="{Binding Tickets}" AutoGenerateColumns="False"
                             IsReadOnly="True"
                             ClipboardCopyMode="IncludeHeader" SelectedItem="{Binding SelectedTicket}"...

<datagrid:ThemedDataGrid.Columns>

            <datagrid:ThemedDataGrid.Columns>
            <DataGridTextColumn Binding="{Binding CrmTicketId}" Header="Ticket Nr." Width="90">
                <DataGridTextColumn.ElementStyle>
                    <Style TargetType="{x:Type TextBlock}">
                        <Setter Property="HorizontalAlignment" Value="Center" />
                    </Style>
                </DataGridTextColumn.ElementStyle>
            </DataGridTextColumn>

            <DataGridTextColumn Binding="{Binding SapAuftrag}" Header="SAP Nr." Width="85">
                <DataGridTextColumn.ElementStyle>
                    <Style TargetType="{x:Type TextBlock}">
                        <Setter Property="HorizontalAlignment" Value="Center" />
                        <Setter Property="Foreground" Value="{Binding ???, Converter={StaticResource SomeBoolToBrushConverter-ToDo}}"/>
                    </Style>
                </DataGridTextColumn.ElementStyle>
            </DataGridTextColumn>

网格绑定到一个列表。

public class SimpleTicketDTO : BaseDTO
{
    public string Kategorie       { get; set; }
    public string Status          { get; set; }
    public string PersonFirmaName { get; set; }
    public bool   HatSAPOrder     { get; set; }
    public string SapAuftrag      { get; set; }
    public bool   DoppelSAPOrder { get; set; }

...

我现在无法访问 ElementStyle 中 Row 的属性“DoppelSAPOrder”:-/

有人可以告诉我如何解决这个问题吗?

标签: wpfmvvmdatagridcell-formatting

解决方案


您希望将元素样式中的 TextBlock 属性绑定到其父行绑定对象,可以使用绑定的 RelativeSource 属性来实现,如下所示:

<DataGridTextColumn Binding="{Binding SapAuftrag}" Header="SAP Nr." Width="85">
    <DataGridTextColumn.ElementStyle>
        <Style TargetType="{x:Type TextBlock}">
           <Setter Property="HorizontalAlignment" Value="Center" />
           <Setter Property="Foreground" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}, Path =Item.DoppelSAPOrder,Converter={StaticResource IsObsoleteToTextDecorationsConverter}}"/>
        </Style>
    </DataGridTextColumn.ElementStyle>
</DataGridTextColumn>

推荐阅读