WPF DataGrid: The selected row is not properly highlighted when using HorizontalAlignment
I have a DataGrid
where one column needs to be aligned to the right. To do this I use
<DataGridTextColumn.CellStyle>
<Style>
<Setter Property="FrameworkElement.HorizontalAlignment" Value="Right"/>
</Style>
</DataGridTextColumn.CellStyle>
which works fine as shown here:
Unfortunately the aligned cells are not properly highlighted when a row is selected. Only the data is highlighted, but the empty area to the left of the data is not, as shown here:
Additionally, the area to the left of the data is not sensitive to mouse-clicks anymore. In the example above, a click to the left of '12.34' will not select the first row (but a click to the right of 'A1' will). Altogether this makes for a bad user experience.
So, how do I do HorizontalAlignment
without breaking row-selection? I want the entire row highlighted, and I want to be able to click anywhere to select a row.
I am using VS 2010, .NET 4, both Win XP and Win 7.
The code to reproduce my example:
namespace WpfApplication2
{
public class ListItem
{
public string FieldA { get; set; }
public decimal FieldB { get; set; }
public string FieldC { get; set; }
}
}
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:My="clr-namespace:WpfApplication2"
Title="MainWindow" Height="350" Width="525">
<Window.Resources&开发者_运维百科gt;
<x:Array x:Key="List" Type="{x:Type My:ListItem}">
<My:ListItem FieldA="A1" FieldB="12.34" FieldC="C1"/>
<My:ListItem FieldA="A2" FieldB="1000.00" FieldC="C2"/>
<My:ListItem FieldA="A3" FieldB="987.6" FieldC="C3"/>
</x:Array>
</Window.Resources>
<Grid>
<DataGrid ItemsSource="{StaticResource List}" AutoGenerateColumns="False" SelectionUnit="FullRow" >
<DataGrid.Columns>
<DataGridTextColumn Header="ColumnA" Binding="{Binding Path=FieldA}" Width="150" />
<DataGridTextColumn Header="ColumnB" Binding="{Binding Path=FieldB, StringFormat='#,##0.00'}" Width="150" >
<DataGridTextColumn.CellStyle>
<Style>
<Setter Property="FrameworkElement.HorizontalAlignment" Value="Right"/>
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="ColumnC" Binding="{Binding Path=FieldC}" Width="*" />
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
Try DataGridTextColumn.ElementStyle
and (if needed) DataGridTextColumn.EditingElementStyle
精彩评论