在WPF数据网格文本列中居中对齐文本时出现间歇性问题。
注意第一个单元格上的左对齐。等待几秒后问题就会自行解决,但是什么原因导致了这个问题呢?我现在已经在几个网格上看到了这个,但不能在一个新项目中有目的地重现这个问题。网格通常在dockpanels,网格和groupbox中有几层深。以下是用于为图示网格设置样式的XAML:
<Style TargetType="DataGrid">
<Setter Property="GridLinesVisibility" Value="None" />
<Setter Property="HorizontalScrollBarVisibility" Value="Hidden" />
<Setter Property="HeadersVisibility" Value="Column" />
</Style>
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="TextBlock.TextAlignment" Value="Center"/>
</Style>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
</Style>
<Style x:Key="GridRowStyle" TargetType="DataGridRow">
<Setter Property="FontSize" Value="14.667" />
<Setter Property="FontFamily" Value="Segoe UI" />
<Setter Property="MinHeight" Value="30" />
<Setter Property="Padding" Value="6,2" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="FocusVisualStyle" Value="{x:Null}" />
</Style>
<Style
x:Key="OrderGridRowStyle"
BasedOn="{StaticResource GridRowStyle}"
TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding Status}" Value="{x:Static desktopViewModels:DisplayableOrderState.Uncommitted}">
<Setter Property="Background" Value="LightGoldenrodYellow" />
</DataTrigger>
</Style.Triggers>
</Style>
这是网格定义:
<DataGrid
x:Name="Orders"
Grid.Row="0"
HorizontalContentAlignment="Center"
AutoGenerateColumns="False"
CanUserAddRows="False"
CanUserReorderColumns="False"
CanUserSortColumns="False"
CurrentItem="{Binding SelectedOrderViewModel, UpdateSourceTrigger=PropertyChanged}"
IsReadOnly="True"
ItemsSource="{Binding OrderViewModels}"
RowStyle="{StaticResource OrderGridRowStyle}"
SelectedItem="{Binding SelectedOrderViewModel, UpdateSourceTrigger=PropertyChanged}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}" Header="Order Name" Width="*"/>
<DataGridTextColumn Binding="{Binding CreatedDate}" Header="Created Date" Width ="*"/>
<DataGridTextColumn Width="*" Binding="{Binding Status}" Header="Status" />
</DataGrid.Columns>
</DataGrid>
我已尝试明确指定列宽而不是使用* width,但问题仍然存在。我已经尝试了其他对网格单元进行居中的方法,如下所示,也没有效果。
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Grid Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Center" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>