Question

I have a WPF Datagrid bounded to a DataSet; Columns are autogenerated. I need to align number columns to the right. I can use a Converter, like in this example I found on the web:

    <DataGrid x:Name="dg" ItemsSource="{Binding Source}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Col}" Header="Col" Width="200">
                <DataGridTextColumn.ElementStyle>
                    <Style TargetType="TextBlock">
                        <Setter Property="TextBlock.HorizontalAlignment" Value="{Binding Col, Converter={StaticResource converter}}" />
                    </Style>
                </DataGridTextColumn.ElementStyle>
            </DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>

But in my case the column are autogenerated, so I can't use

<DataGrid.Columns>

And I don't know how to bind the property

<Setter Property="TextBlock.HorizontalAlignment" Value="{Binding Col, Converter={StaticResource converter}}" />

Any solution?

Was it helpful?

Solution

This may not be an ideal solution, but you could try and set the ElementStyle for each column after they have been generated by hooking a handler to AutoGeneratedColumns event.

This is what I tried:

Style

<Style TargetType="TextBlock" x:Key="ColumnStyle">
    <Setter Property="HorizontalAlignment" Value="{Binding Path=Text, RelativeSource={RelativeSource Self}, Converter={StaticResource AlignmentConverter}}" />
</Style>

XAML for DataGrid

<DataGrid x:Name="dg" 
          ItemsSource="{Binding Items}" 
          AutoGenerateColumns="True" 
          AutoGeneratedColumns="Dg_OnAutoGeneratedColumns" 
          SelectionMode="Extended"/>

EventHandler Code (Code Behind)

void Dg_OnAutoGeneratedColumns(object sender, EventArgs e)
{
    foreach (var dataGridColumn in dg.Columns)
    {
        var textColumn = dataGridColumn as DataGridTextColumn;
        if (textColumn == null) continue;

        textColumn.ElementStyle = FindResource("ColumnStyle") as Style;
    }
}

If you do not like Code Behind, then you can always create an attached behavior to achieve the same result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top