Moh*_*dil 90
如果您使用的是DataGridTextColumn,则可以使用以下代码段:
<Style TargetType="DataGridCell">
<Style.Setters>
<Setter Property="TextBlock.TextAlignment" Value="Center" />
</Style.Setters>
</Style>
Run Code Online (Sandbox Code Playgroud)
Ken*_*art 48
不知道具体细节很难说,但这是一个DataGridTextColumn
集中的:
<wpf:DataGridTextColumn Header="Name" Binding="{Binding Name}" IsReadOnly="True">
<wpf:DataGridTextColumn.CellStyle>
<Style>
<Setter Property="FrameworkElement.HorizontalAlignment" Value="Center"/>
</Style>
</wpf:DataGridTextColumn.CellStyle>
</wpf:DataGridTextColumn>
Run Code Online (Sandbox Code Playgroud)
Jan*_*Jan 19
我从huttelihut的解决方案开始.不幸的是,这对我来说还不适用.我调整了他的答案并想出了这个(解决方案是将文本对齐):
<Resources>
<Style x:Key="RightAligned" TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Right"/>
</Style>
</Resources>
Run Code Online (Sandbox Code Playgroud)
如您所见,我将样式应用于TextBlock,而不是DataGridCell.
然后我必须设置元素样式,而不是单元格样式.
ElementStyle="{StaticResource RightAligned}"
Run Code Online (Sandbox Code Playgroud)
T.J*_*aer 14
为Kent Boogaart +1.我最终做到了这一点,这使代码稍微混乱(并使我能够在几列上使用对齐):
<Resources>
<Style x:Key="NameCellStyle" TargetType="DataGridCell">
<Setter Property="HorizontalAlignment" Value="Center" />
</Style>
</Resources>
<DataGrid.Columns>
<DataGridTextColumn Header="Name" CellStyle="{StaticResource NameCellStyle}" Binding="{Binding Name}"/>
// .. other columns
</DataGrid.Columns>
Run Code Online (Sandbox Code Playgroud)
这是@ MohammedAFadil的XAML答案,转换为C#代码:
var MyStyle = new Style(typeof(DataGridCell)) {
Setters = {
new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Center)
}
};
Run Code Online (Sandbox Code Playgroud)
要应用Style
,请设置例如的CellStyle
属性DataGrid
var MyGrid = new DataGrid() {
CellStyle = MyStyle
};
Run Code Online (Sandbox Code Playgroud)
小智 5
或者在后面的代码中:
grid.CellStyle = newCellStyle();
public static Style newCellStyle()
{
//And here is the C# code to achieve the above
System.Windows.Style style = new Style(typeof(DataGridCell));
style.Setters.Add(new System.Windows.Setter
{
Property = Control.HorizontalAlignmentProperty,
Value = HorizontalAlignment.Center
});
return style;
}
Run Code Online (Sandbox Code Playgroud)
我最终遇到了单元格移动的问题,并且使用接受的答案看起来很时髦。我知道已经晚了,但希望我的发现能对某人有所帮助。我用:
<DataGridTextColumn.ElementStyle>
<Style>
<Setter Property="FrameworkElement.HorizontalAlignment" Value="Center"/>
</Style>
Run Code Online (Sandbox Code Playgroud)
而不是单元格样式。
归档时间: |
|
查看次数: |
65069 次 |
最近记录: |