tags:

views:

843

answers:

2

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 have padding, and all the stuff in column 2 to be aligned right. It seems to be very non-WPF to have to set those properties on each item in the grid.

I know I can create a style for all TextBlocks within a grid by doing something like this:

<Grid>
  <Grid.Resources>
    <Style TargetType="{x:Type TextBox}">
      <Setter Property="HorizontalAlignment" Value="Right"/>
    </Style>
  </Grid.Resources>
</Grid>

But is there a way to apply that style to only the controls in say, column 2?

Should I be using a different control?

A: 

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>
sacha
Is this only for DataGrid? I can't see how to apply this to a Grid.
Jacob Stanley
You can assign the style to each column. See the edited code.
sacha
I was looking for how to do this with a standard Grid, but i'll take a look in to DataGrid and see if I can use this instead.
Jacob Stanley
+1  A: 

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>
Bryan Anderson
That's exactly what I was looking for! Nice and elegant too, why didn't I think of that :)
Jacob Stanley