如何使用转换器或数据触发器在数据网格的列中动态设置单元格样式?

how could I set the cell style in a column in a datagrid dynamically with converter or datatrigger?

我想根据数据行中的一条数据动态设置datagrid某列某行的样式,所以根据那个属性的值,只有一个属性, 我想在资源字典中的 3 种不同样式中进行选择。

我正在尝试这个解决方案:

<DataGridTextColumn.CellStyle>
    <Style TargetType="DataGridCell" BasedOn="{StaticResource ResourceKey=DataGridCellLeftHorizontalAlignment}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding NumeroLineaFactura}" Value="-1">
                <Setter Property="FontWeight" Value="Bold"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</DataGridTextColumn.CellStyle>

但这有一个问题,我只能select其中一种样式,我必须一个一个地更改其余属性,所以我必须如何在各个列中设置样式,它让我重复代码。

我想 select 使用数据触发器或转换器的样式,但我不知道可以做到的语法,因为在触发器中我可以设置 属性 CellStyle 都没有样式。

如何动态设置单元格样式?

谢谢。

因为没有可用的 CellStyleSelector 属性 并且您不能使用 DataTrigger 来更改 Style 本身,您应该使用单个 Style然后使用几个 DataTriggers 来改变 DataGridCell 的属性,例如:

 <Style TargetType="DataGridCell">
    <Style.Triggers>
        <DataTrigger Binding="{Binding NumeroLineaFactura}" Value="-1">
            <Setter Property="FontWeight" Value="Bold"/>
            <Setter Property="TextAlignment" Value="Right"/>
        </DataTrigger>
    </Style.Triggers>
</Style>

Thanks. In this case it works, but if I have another column that for the -1 value has the same style, I have to repeat the code...

没错。在这种情况下,您可以考虑实现自己的自定义 DataGridTextColumn 并以编程方式设置 CellStyle。像这样:

public class CustomDataGridTextColumn : DataGridTextColumn
{
    public static readonly DependencyProperty FirstStyleProperty = DependencyProperty.Register(
        name: nameof(FirstStyle),
        propertyType: typeof(Style),
        ownerType: typeof(CustomDataGridTextColumn)));

    public Style FirstStyle
    {
        get => (Style)GetValue(FirstStyleProperty);
        set => SetValue(FirstStyleProperty, value);
    }

    //...

    protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
    {
        FrameworkElement element = base.GenerateElement(cell, dataItem);

        var val = dataItem as YourClass;
        if(val != null)
        {
            switch (val.NumeroLineaFactura)
            {
                case -1:
                    cell.Style = FirstStyle;
                    break;
                //...
            }
        }

        return element;
    }
}

XAML::

<DataGrid.Columns>
    <local:CustomDataGridTextColumn ... FirstStyle="{StaticResource yourFirstStyle}" />
</DataGrid.Columns>