完美解決在wpf datagrid讓列標題居中以及列內容居中
阿新 • • 發佈:2019-01-24
一般我們要實現居中設定 HorizontalContentAlignment="Center" VerticalContentAlignment="Center"就可以了, 但是datagrid的DataGridTextColumn中卻發現沒有HorizontalContentAlignment或者HorizontalAlignment,列中的內容仍然是左對齊,如何處理才能居中呢?
// 右對齊風格 Style styleRight = new Style(typeof(TextBlock)); Setter setRight = new Setter(TextBlock.HorizontalAlignmentProperty, HorizontalAlignment.Right);styleRight.Setters.Add(setRight); foreach (DataGridColumn c in yourDataGrid.Columns) { DataGridTextColumn tc = c as DataGridTextColumn; if (tc != null) { tc.ElementStyle = styleRight; } }
即只要設定DataGridColumn的ElementStyle就可以了,也可以在xaml中設定
<Style x:Key="contentCenterStyle"
TargetType="{x:Type TextBlock}">
<Setter Property="HorizontalAlignment"
Value="Center" />
</Style>
<DataGridTextColumn Header="程式碼" ElementStyle="{StaticResource contentCenterStyle}" Binding="{Binding Name}"></DataGridTextColumn>