对某些数据网格列应用WPF样式

本文关键字:应用 WPF 样式 网格 数据网 数据 | 更新日期: 2023-09-27 18:04:39

我有这个DataGrid

<DataGrid Name="OrderItemList" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Code" Binding="{Binding Code}" IsReadOnly="True" />
        <DataGridTextColumn Header="Color" IsReadOnly="True" />
        <DataGridTextColumn Header="Size" IsReadOnly="True" />
        <DataGridTextColumn Header="Price" Binding="{Binding Price`}" IsReadOnly="True" />
        <DataGridTextColumn Header="Qty" Binding="{Binding Qty}" />
        <DataGridTemplateColumn Header="">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button>Remove</Button>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>    
        <DataGridTextColumn Header="" Width="*" IsReadOnly="True" />
    </DataGrid.Columns>
</DataGrid>

这是我的风格

<Style x:Key="TextColumn" TargetType="{x:Type DataGridCell}">
    <Style.Triggers>
        <Trigger Property="DataGridCell.IsSelected" Value="True">
            <Setter Property="Background" Value="#F1F1F1" />
        </Trigger>
    </Style.Triggers>
    <Setter Property="Padding" Value="10" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type DataGridCell}">
                <TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content.Text, Mode=TwoWay, UpdateSourceTrigger=Default}"
                    HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Padding="{TemplateBinding Padding}" Background="{TemplateBinding Background}"
                    BorderThickness="0" IsReadOnly="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Column.IsReadOnly}" />
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

我怎么能应用这种风格只有DataGridTextColumn的单元格?

对某些数据网格列应用WPF样式

您可以简单地在DataGridTextColumn定义中设置CellStyle属性。

<DataGridTextColumn CellStyle="{StaticResource TextColumn}" ...