tags:

views:

2330

answers:

2

It taking 5 lines to right-align a DataGridTextColumn is bloating my XAML.

How can I put this "right-align code block" into a style and call it from an attribute, e.g. class="rightAlignDataGridTextColumn".

<toolkit:DataGridTextColumn Header="Order Date" Width="Auto"
       Binding="{Binding OrderDate, StringFormat='{}{0:dd.MM.yyyy}'}" 
       IsReadOnly="False">
    <toolkit:DataGridTextColumn.ElementStyle>
        <Style TargetType="TextBlock">
            <Setter Property="TextAlignment" Value="Right" />
        </Style>
    </toolkit:DataGridTextColumn.ElementStyle>
</toolkit:DataGridTextColumn>

<toolkit:DataGridTextColumn Header="Required Date" Width="Auto"
       Binding="{Binding RequiredDate, StringFormat='{}{0:dd.MM.yyyy}'}" 
       IsReadOnly="False">
    <toolkit:DataGridTextColumn.ElementStyle>
        <Style TargetType="TextBlock">
            <Setter Property="TextAlignment" Value="Right" />
        </Style>
    </toolkit:DataGridTextColumn.ElementStyle>
</toolkit:DataGridTextColumn>

<toolkit:DataGridTextColumn Header="Shipped Date" Width="Auto"
       Binding="{Binding ShippedDate, StringFormat='{}{0:dd.MM.yyyy}'}" 
       IsReadOnly="False">
    <toolkit:DataGridTextColumn.ElementStyle>
        <Style TargetType="TextBlock">
            <Setter Property="TextAlignment" Value="Right" />
        </Style>
    </toolkit:DataGridTextColumn.ElementStyle>
</toolkit:DataGridTextColumn>
+3  A: 

Declare the Style in a ResourceDictionary, like so:

<Window.Resources>
    <Style x:Key="RightAlignStyle" TargetType="{x:Type TextBlock}">
        <Setter Property="TextAlignment" Value="Right" />
    </Style>
</Window.Resources>

Then reference this style on each DataGridTextColumn element:

<toolkit:DataGridTextColumn ElementStyle="{StaticResource RightAlignStyle}" ... >
Bradley Grainger
perfect, thanks!
Edward Tanguay
A: 

Thanks Bradley. I also wanted multiple styles for one DataGridTextColumn. this helped http://stackoverflow.com/questions/16096/how-to-apply-multiple-styles-in-wpf

Vaishnavi