WPF 数据网格 : The selected row is not properly highlighted when using HorizontalAlignment

标签 wpf xaml datagrid alignment

我有一个 DataGrid,其中一列需要右对齐。为此,我使用

<DataGridTextColumn.CellStyle>
  <Style>
    <Setter Property="FrameworkElement.HorizontalAlignment" Value="Right"/>
  </Style>
</DataGridTextColumn.CellStyle>

如下所示,效果很好:

enter image description here

不幸的是,选中一行时对齐的单元格没有正确突出显示。只有数据高亮显示,但数据左侧的空白区域没有高亮显示,如下所示:

enter image description here

此外,数据左侧的区域不再对鼠标点击敏感。在上面的示例中,单击“12.34”左侧不会选择第一行(但单击“A1”右侧会)。总之,这会导致糟糕的用户体验。

那么,如何在不中断行选择的情况下执行 Horizo​​ntalAlignment?我希望整行突出显示,并且我希望能够在任意位置单击以选择一行。

我正在使用 VS 2010、.NET 4、Win XP 和 Win 7。

重现示例的代码:

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>
        <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>

最佳答案

尝试 DataGridTextColumn.ElementStyle 和(如果需要)DataGridTextColumn.EditingElementStyle

关于WPF 数据网格 : The selected row is not properly highlighted when using HorizontalAlignment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5726296/

相关文章:

c# - 如何使用 RepeatBehaviour 停止 Storyboard ="Forever"

c# - WPF 依赖属性

xaml - 如何在Xamarin中调用API在UI上显示数据

c# - 如何使 DataGrid 列随着控件宽度的变化而拉伸(stretch)?

WPF - 自定义控件 + ICommand(如何实现)?

wpf - 如何格式化标签以具有显示格式字符串?

wpf - C# WPF 在构建时创建了太多文化文件夹

.Net 在运行时重新排序 DataGridView 列

WPF DataGrid 为每个列集添加单独的边框

c# - 编辑后未清除 WPF Datagrid 行验证错误