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

前端 未结 2 1405
孤城傲影
孤城傲影 2020-12-30 05:46

I have a WPF Grid with many rows and columns, all containing things like TextBlocks and TextBoxes.

For this specific situation I want all the stuff in column 1 to ha

相关标签:
2条回答
  • 2020-12-30 06:10

    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>
    
    0 讨论(0)
  • 2020-12-30 06:22

    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>
    
    0 讨论(0)
提交回复
热议问题