WPF - XAML使DataGridTextColumnsElements对齐到中心
本文关键字:对齐 DataGridTextColumnsElements XAML WPF | 更新日期: 2023-09-27 18:10:17
是否有一种方法来全局对齐DataGridTextColumns中的文本到中间或中心?
为每个DataGrid执行此操作的示例是
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="HorizontalAlignment"
Value="Center" />
</Style>
</DataGridTextColumn.ElementStyle>
但是我不想为每个DataGrid复制粘贴这些代码,我喜欢在app.xaml文件中这样做。
我正在寻找类似(但不工作)的东西
<Style TargetType="{x:Type DataGridTextColumn.ElementStyle}">
<Setter Property="HorizontalAlignment" Value="Center"/>
</Style>
Put styles在一个资源字典中,在App.xaml中引用。
xmlns:dg="clr-namespace:Microsoft.Windows.Controls.Primitives;assembly=WPFToolkit"
<Style x:Key="DataGridColumnHeaderStyle" TargetType="{x:Type dg:DataGridColumnHeader}" >
<Setter Property="HorizontalContentAlignment"
Value="Center" />
</Style>
您可以创建一个User控件,它封装您的自定义网格,并在需要的地方重用它。
为所有DataGridTextColumn
定义一个全局样式可能是不可能的,因为DataGridTextColumn
不是FrameworkElement
,而Style.TargetType
只允许从FrameworkElement
派生的类型。
DataGridCell
应用格式化,如:
<Application x:Class="yourprojectname.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="yourstartupuri.xaml">
<Application.Resources>
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="TextBlock.TextAlignment" Value="Center"/>
</Style>
</Application.Resources>
</Application>