为DataGridTextColumn设置表头样式和单元格样式

为DataGridTextColumn设置表头样式和单元格样式
方法是把样式作为全局资源使用。

1、在App.xaml中引用命名空间
    xmlns:Primitives="clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Data"
    xmlns:Controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
2、添加全局资源
   <Application.Resources>
        <!--DataGrid-->
        <!--表头样式-->
        <Style x:Key="DataGrid_Header_Left" TargetType="Primitives:DataGridColumnHeader">
            <Setter Property="VerticalAlignment" Value="Center" />
            <Setter Property="HorizontalContentAlignment" Value="Left" />
        </Style>
        <Style x:Key="DataGrid_Header_Center" TargetType="Primitives:DataGridColumnHeader">
            <Setter Property="VerticalAlignment" Value="Center" />
            <Setter Property="HorizontalContentAlignment" Value="Center" />
        </Style>
        <Style x:Key="DataGrid_Header_Right" TargetType="Primitives:DataGridColumnHeader">
            <Setter Property="VerticalAlignment" Value="Center" />
            <Setter Property="HorizontalContentAlignment" Value="Right" />
        </Style>
        
        <!--单元格样式-->
        <Style x:Key="DataGrid_Cell_Left" TargetType="Controls:DataGridCell">
            <Setter Property="HorizontalContentAlignment" Value="Left" />
        </Style>
        <Style x:Key="DataGrid_Cell_Center" TargetType="Controls:DataGridCell">
            <Setter Property="HorizontalContentAlignment" Value="Center" />
        </Style>
        <Style x:Key="DataGrid_Cell_Right" TargetType="Controls:DataGridCell">
            <Setter Property="HorizontalContentAlignment" Value="Right" />
        </Style>
    </Application.Resources>
3、为指定列设置样式
(1)、静态设置方法:
    <data:DataGridTextColumn Width="70" Header="材料单位" HeaderStyle="{StaticResource DataGrid_Header_Center}" CellStyle="{StaticResource DataGrid_Cell_Center}"  />
(2)、动态设置方法:
    Col.CellStyle = ZJSJFX.Silverlight.App.Current.Resources["DataGrid_Cell_Right"] as Style;

你可能感兴趣的:(datagrid)