WPF Grid - How to apply a style for just one column?

走远了吗. 提交于 2019-11-30 09:13:27
Bryan Anderson

Here's what I usually do:

<Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource {x:Type TextBlock}}">
    <Style.Triggers>
        <Trigger Property="Grid.Column" Value="0">
            <Setter Property="Margin" Value="0,0,2,0" />
        </Trigger>

        <Trigger Property="Grid.Column" Value="2">
            <Setter Property="Margin" Value="20,0,2,0" />
        </Trigger>
    </Style.Triggers>
</Style>

You can define some styles like below and assign them to your Column.ElementStyle property:

<Window.Resources>
       <Style x:Key="elementStyle" TargetType="TextBlock">
           <Setter Property="VerticalAlignment" Value="Center" />
           <Setter Property="Margin" Value="2,0,2,0" />
       </Style>

       <Style x:Key="rightElementStyle" BasedOn="{StaticResource elementStyle}" TargetType="TextBlock">
           <Setter Property="HorizontalAlignment" Value="Right" />
       </Style>

       <Style x:Key="centerElementStyle" BasedOn="{StaticResource elementStyle}" TargetType="TextBlock">
           <Setter Property="HorizontalAlignment" Value="Center" />
       </Style>
</Window.Resources>

<dg:DataGrid AutoGenerateColumns="False">
      <dg:DataGrid.Columns>
           <dg:DataGridTextColumn Binding={Binding Path=Name} 
                                  Header="Name" 
                                  ElementStyle="{StaticResource centerElementStyle}"/>
           <dg:DataGridTextColumn Binding={Binding Path=Amount} 
                                  Header="Amount" 
                                  ElementStyle="{StaticResource rightElementStyle}"/>
    </dg:DataGrid.Columns>
</dg:DataGrid>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!