How to get a WPF DataGrid cell to right align without making the selectable area on a new row tiny?
Solution 1:
You could apply ElementStyle
on the DataGridTextColumn
targetted to TextBlock
and right align that, it would work.
<DataGridTextColumn Binding="{Binding Path=ImpaId}">
<DataGridTextColumn.Header>
<TextBlock Style="{StaticResource
DataGridHeader}">
Impa
</TextBlock>
</DataGridTextColumn.Header>
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="HorizontalAlignment" Value="Right" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
Solution 2:
Just wanted to add to more examples for future code searches.
I put this in the top of the xaml file:
<UserControl.Resources>
<Style TargetType="{x:Type TextBlock}" x:Key="RightCell">
<Setter Property="Background" Value="{Binding Included, Converter={StaticResource BoolToColorConverter}}"/>
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="TextAlignment" Value="Right"/>
</Style>
</UserControl.Resources>
And then in the datagrid:
<DataGridTextColumn Header="Excluded" Binding="{Binding Excluded}" ElementStyle="{StaticResource RightCell}"/>
This right aligns the text and sorting is still enabled. The textbox fills the cell and in this case is colored using a bool converter.
Solution 3:
You can try a work around :
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid Background="White" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<TextBlock HorizontalAlignment="Right" Text="{Binding Path=ImpaId}"/>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>