2011-11-30 122 views
3

我想在DataGrid中創建數據記錄的VerticalAlignment=Center。默認情況下,數據記錄的VerticalAlignment=Top,它看起來醜陋。你能爲我提供這種風格嗎?如何在WPF DataGrid中垂直居中行的內容?

我在App.xaml文件中定義了我的樣式。以下是我目前的DataGrid風格:

<Style x:Key="DataGridView" TargetType="DataGrid"> 
     <Setter Property="AlternatingRowBackground" Value="AliceBlue"></Setter> 
     <Setter Property="AlternationCount" Value="1"></Setter> 
     <Setter Property="AutoGenerateColumns" Value="False"></Setter> 
     <Setter Property="GridLinesVisibility" Value="Horizontal"></Setter> 
     <Setter Property="VerticalGridLinesBrush" Value="DarkGray"></Setter> 
     <Setter Property="HorizontalGridLinesBrush" Value="DarkGray"></Setter> 
     <Setter Property="RowHeight" Value="32"></Setter> 
    </Style> 

回答

8

嘗試在DataGrid設置VerticalContentAlignment="Center"

<DataGrid VerticalContentAlignment="Center"> 
    ... 
</DataGrid> 

,或者你可以一個setter添加到您的風格:

<Setter Property="VerticalContentAlignment" Value="Center"/> 

當應用於ItemsControl s,這個屬性通常會修改每個單獨的物品容器的對齊。在你的情況下,這應該使所有行的內容居中對齊。

UPDATE

好像內置DataGrid不遵守規則的WPF。

解決方案取決於您使用的列的類型。

對於DataGridTemplateColumn使用CellTemplate這樣的:

<DataTemplate> 
    <!--Substitute the TextBlock by the actual cell content, but don't drop VerticalAlignment--> 
    <TextBlock VerticalAlignment="Center" Text="{Binding Text}"/> 
</DataTemplate> 

對於DataGridTextColumn,設置ElementStyle

<Style> 
    <Setter Property="FrameworkElement.VerticalAlignment" Value="Center"/> 
</Style> 

我已經試過這對DataGridTextColumn,但屬性是從其父DataGridBoundColumn,所以也應該爲DataGridCheckBoxColumnDataGridHyperlinkColumn工作。

更新2

BTW,there's another solution

+0

嗨帕維爾Gatilov,我嘗試在我的風格setters列表中添加VerticalContentAlignment =「中心」,但它似乎沒有效果。 –

+0

順便說一下,DataGrid中的列是由我的csharp代碼創建的,而不是由控件本身自動生成的。因爲我的ItemsSource是DataView,我無法知道我想要顯示的列(它們來自數據庫,列是動態的)。 –

+0

@qingxu請看我更新的帖子。我已經嘗試了這兩種選擇,他們確實有效。唯一可能的是,你可能無法將它包含到DataGrid的'Style'中,但是當你創建列時你應該能夠分配屬性。 –