如何使用名称 属性 覆盖 WPF 中特定列的数据网格单元格?

How to override data grid cells of a specific column in WPF using some property like Name?

基本上现在我正在使用列显示索引,但每次我添加或删除列或更改它们的顺序时都会搞砸。

我无法使用列文本,因为列文本通过绑定具有动态文本,所以我正在查看 x:Name 属性,但我不确定如何在发布的示例中使用它代码。例如没有Column.Name

        <DataGridTemplateColumn Header="S" Width="24" SortMemberPath="Price" x:Name="Price">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Ellipse Width="{Binding Balance.SpotBalanceSize}" Height="{Binding Balance.SpotBalanceSize}" Fill="{Binding Path=Balance.SpotBalanceColor}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

        <MultiDataTrigger>
            <MultiDataTrigger.Conditions>
                <Condition Binding="{Binding Column.DisplayIndex, RelativeSource={RelativeSource Self}}" Value="16"/>
            </MultiDataTrigger.Conditions>
            <MultiDataTrigger.Setters>
                <Setter Property="DataGridCell.Background" Value="{Binding Path=PriceChangeHourlyBackColor}" />
                <Setter Property="DataGridCell.Foreground" Value="{Binding Path=PriceChangeHourlyForeColor}" />
            </MultiDataTrigger.Setters>
        </MultiDataTrigger>

您可以通过绑定到附件来解决它 属性:

<DataGridTemplateColumn Header="S" Width="24" SortMemberPath="Price" local:AttachedClass.ColName="JoanVenge">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Ellipse Width="{Binding Balance.SpotBalanceSize}" Height="{Binding Balance.SpotBalanceSize}" Fill="{Binding Path=Balance.SpotBalanceColor}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

<MultiDataTrigger>
    <MultiDataTrigger.Conditions>
        <Condition Binding="{Binding Column.(local:AttachedClass.ColName), RelativeSource={RelativeSource Self}}" Value="JoanVenge"/>
    </MultiDataTrigger.Conditions>
    <MultiDataTrigger.Setters>
        <Setter Property="DataGridCell.Background" Value="{Binding Path=PriceChangeHourlyBackColor}" />
        <Setter Property="DataGridCell.Foreground" Value="{Binding Path=PriceChangeHourlyForeColor}" />
    </MultiDataTrigger.Setters>
</MultiDataTrigger>

public class AttachedClass
{
    public static string GetColName(DependencyObject obj)
    {
        return (string)obj.GetValue(ColNameProperty);
    }

    public static void SetColName(DependencyObject obj, string value)
    {
        obj.SetValue(ColNameProperty, value);
    }

    public static readonly DependencyProperty ColNameProperty = DependencyProperty.RegisterAttached("ColName", typeof(string), typeof(AttachedClass), new PropertyMetadata(""));
}