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

时间:2015-07-24 09:50:53

标签: c# .net wpf

我有这个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的单元格?

1 个答案:

答案 0 :(得分:1)

您只需在CellStyle定义上设置DataGridTextColumn属性即可。

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