我有幾列是數字並希望它們右對齊。這是一個有點做作的例子來展示我的問題:將默認資源樣式應用於所有DataGridTextColumns
<Window x:Class="MyApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Controls="clr-namespace:System.Windows.Controls;assembly=PresentationFramework" xmlns:Windows="clr-namespace:System.Windows;assembly=PresentationFramework" xmlns:Data="clr-namespace:System.Windows.Data;assembly=PresentationFramework" Title="MyApp"
Width="Auto" Height="Auto" SizeToContent="WidthAndHeight" Loaded="Window_Loaded">
<Controls:DataGrid Name="MyDataGrid" IsReadOnly="True"
xmlns="http://schemas.microsoft.com/wpf/2008/toolkit" ItemsSource="{Data:Binding}" AutoGenerateColumns="True">
<Controls:DataGrid.Columns>
<!-- This is a product name and is left justified by default -->
<Controls:DataGridTextColumn Header="ProductName" Binding="{Data:Binding Path=ProductName}" />
<!-- The rest of the columns are numeric and I would like for them to be right justified -->
<Controls:DataGridTextColumn Header="ProductId1" Binding="{Data:Binding Path=ProductId1}" >
<Controls:DataGridTextColumn.ElementStyle>
<Windows:Style TargetType="Controls:TextBlock">
<Windows:Setter Property="HorizontalAlignment" Value="Right"/>
</Windows:Style>
</Controls:DataGridTextColumn.ElementStyle>
</Controls:DataGridTextColumn>
<Controls:DataGridTextColumn Header="ProductId2" Binding="{Data:Binding Path=ProductId2}" >
<Controls:DataGridTextColumn.ElementStyle>
<Windows:Style TargetType="Controls:TextBlock">
<Windows:Setter Property="HorizontalAlignment" Value="Right"/>
</Windows:Style>
</Controls:DataGridTextColumn.ElementStyle>
</Controls:DataGridTextColumn>
<Controls:DataGridTextColumn Header="ProductId3" Binding="{Data:Binding Path=ProductId3}" >
<Controls:DataGridTextColumn.ElementStyle>
<Windows:Style TargetType="Controls:TextBlock">
<Windows:Setter Property="HorizontalAlignment" Value="Right"/>
</Windows:Style>
</Controls:DataGridTextColumn.ElementStyle>
</Controls:DataGridTextColumn>
<!-- More numeric columns follow... -->
</Controls:DataGrid.Columns>
</Controls:DataGrid>
</Window>
右對齊樣式重複所有,但第一列和似乎是多餘的。如果只有我可以在這個網格中設置DataGridTextColumns是正確的,那麼我只需要明確地左對齊第一列。我怎麼能做到這一點,也許使用風格作爲資源?有沒有更好的辦法?