wpf 如何根据DataGridColumn的类型对齐DatagridColumnHeader文本?

dffbzjpn  于 2023-05-19  发布在  其他
关注(0)|答案(1)|浏览(149)

我有下面的代码,我希望DataGrid头文本在它是DataGridComboBoxColumn时左对齐,在它不是DataGridComboBoxColumn时居中。
风格触发器应该起作用,但它们没有。我应该怎么做?
<Window.Resources>

<Style  x:Key="CustomColumnHeaderStyle1" TargetType="{x:Type DataGridColumnHeader}">
        <Setter Property="HorizontalContentAlignment"  Value="Center" />
        <Setter Property="Width" Value="200"/>
        <Style.Triggers>
            <DataTrigger Binding="{Binding DataContext, RelativeSource={RelativeSource Self}}" Value="{x:Type DataGridComboBoxColumn}">
                <Setter Property="HorizontalContentAlignment" Value="Left" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
    <Style  x:Key="CustomColumnHeaderStyle2" TargetType="{x:Type DataGridColumnHeader}">
        <Setter Property="HorizontalContentAlignment" Value="Center" />
        <Setter Property="Width" Value="200"/>
        <Style.Triggers>
            <DataTrigger Binding="{Binding Column}" Value="{x:Type DataGridComboBoxColumn}">
                <Setter Property="HorizontalContentAlignment" Value="Left" />
            </DataTrigger>
        </Style.Triggers>
    </Style>

    <ObjectDataProvider x:Key="myEnum" MethodName="GetValues" ObjectType="{x:Type core:Enum}">
        <ObjectDataProvider.MethodParameters>
            <x:Type Type="local:OrderStatus"/>
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
</Window.Resources>
<Window.DataContext>
    <local:ViewModel/>
</Window.DataContext>
<Grid>
    <DataGrid ItemsSource="{Binding MyData}"  AutoGenerateColumns="False"
              ColumnHeaderStyle="{StaticResource CustomColumnHeaderStyle2}">
        <DataGrid.Columns>
            <DataGridComboBoxColumn Header="Order Status"  SelectedItemBinding="{Binding Status}" ItemsSource="{Binding Source={StaticResource myEnum}}" />

            <DataGridTextColumn Header="Text Column" Binding="{Binding Name}"/>
        </DataGrid.Columns>
    </DataGrid>

</Grid>
3okqufwl

3okqufwl1#

样式触发器应该起作用
不可以。Column属性不返回类型。列不是某个东西的DataContext
您无法仅使用数据触发器和绑定来解决此问题。
只需将所有DataGridComboBoxColumnsHeaderStyle设置为以下样式:

<Style x:Key="CenteredCustomColumnHeaderStyle" TargetType="{x:Type DataGridColumnHeader}">
    <Setter Property="HorizontalContentAlignment" Value="Center" />
</Style>

示例:

<DataGridComboBoxColumn Header="Order Status"  SelectedItemBinding="{Binding Status}"
                        ItemsSource="{Binding Source={StaticResource myEnum}}"
                        HeaderStyle="{StaticResource CenteredCustomColumnHeaderStyle}"/>

相关问题