C# WPF DataGrid 隔行变色及内容居中对齐。

dqzww NET学习0

 
 

先看效果:

前台XAML代码:

<!--引入样式文件-->

<Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary  Source="/Css/DataGridCss.xaml"/>
            </ResourceDictionary.MergedDictionaries>
            <Style x:Key="contentCenterStyle" TargetType="{x:Type TextBlock}">
                <Setter Property="VerticalAlignment" Value="Center" />
            </Style>
        </ResourceDictionary>
    </Window.Resources>

<!--XAML中DataGrid-->

<DataGrid AutoGenerateColumns="False" Name="dataGrid1" VerticalAlignment="Top" CanUserSortColumns="False" Width="660" Margin="5" IsReadOnly="True" CanUserResizeColumns="False" CanUserResizeRows="False" SelectionMode="Single" CanUserReorderColumns="False" AlternationCount="2" RowHeaderWidth="0" CanUserAddRows="False" >

<DataGrid.Columns>

<DataGridTextColumn Header="名称" Width="150" Binding="{Binding Name}"/>

<DataGridTextColumn Header="最新价" Width="120" Binding="{Binding Zxj}"/>

<DataGridTextColumn Header="涨跌" Width="120" Binding="{Binding Zd}"/>

<DataGridTextColumn Header="涨幅" Width="130" Binding="{Binding Zf}"/>

<DataGridTextColumn Header="短线强势股" Width="140" Binding="{Binding Dxqsg}"/>

</DataGrid.Columns>

</DataGrid>

前台XAML的风格代码

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="DataGrid">
        <!--网格线颜色-->
        <Setter Property="CanUserResizeColumns" Value="false"/>
        <Setter Property="Background" Value="#E6DBBB" />
        <Setter Property="BorderBrush" Value="#d6c79b" />
        <Setter Property="HorizontalGridLinesBrush">
            <Setter.Value>
                <SolidColorBrush Color="#d6c79b"/>
            </Setter.Value>
        </Setter>
        <Setter Property="VerticalGridLinesBrush">
            <Setter.Value>
                <SolidColorBrush Color="#d6c79b"/>
            </Setter.Value>
        </Setter>
    </Style>

<!--标题栏样式-->
    <!--<Style  TargetType="DataGridColumnHeader" >
        <Setter Property="Width" Value="50"/>
        <Setter Property="Height" Value="30"/>
        <Setter Property="FontSize" Value="14" />
        <Setter Property="Background" Value="White" />
        <Setter  Property="FontWeight"  Value="Bold"/>
    </Style>-->

<Style TargetType="DataGridColumnHeader">
        <Setter Property="SnapsToDevicePixels" Value="True" />
        <Setter Property="MinWidth" Value="0" />
        <Setter Property="MinHeight" Value="28" />
        <Setter Property="Foreground" Value="#323433" />
        <Setter Property="FontSize" Value="14" />
        <Setter Property="Cursor" Value="Hand" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="DataGridColumnHeader">
                    <Border x:Name="BackgroundBorder" BorderThickness="0,1,0,1"
                             BorderBrush="#e6dbba"
                              Width="Auto">
                        <Grid >
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*" />
                            </Grid.ColumnDefinitions>
                            <ContentPresenter  Margin="0,0,0,0" VerticalAlignment="Center" HorizontalAlignment="Center"/>
                            <Path x:Name="SortArrow" Visibility="Collapsed" Data="M0,0 L1,0 0.5,1 z" Stretch="Fill"  Grid.Column="2" Width="8" Height="6" Fill="White" Margin="0,0,50,0"
                            VerticalAlignment="Center" RenderTransformOrigin="1,1" />
                            <Rectangle Width="1" Fill="#d6c79b" HorizontalAlignment="Right" Grid.ColumnSpan="1" />
                            <!--<TextBlock  Background="Red">
                            <ContentPresenter></ContentPresenter></TextBlock>-->
                        </Grid>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="Height" Value="25"/>
    </Style>
    <!--行样式触发-->
    <!--背景色改变必须先设置cellStyle 因为cellStyle会覆盖rowStyle样式-->
    <Style  TargetType="DataGridRow">
        <Setter Property="Background" Value="#F2F2F2" />
        <Setter Property="Height" Value="25"/>
        <Setter Property="Foreground" Value="Black" />
        <Style.Triggers>
            <!--隔行换色-->
            <Trigger Property="AlternationIndex" Value="0" >
                <Setter Property="Background" Value="#e7e7e7" />
            </Trigger>
            <Trigger Property="AlternationIndex" Value="1" >
                <Setter Property="Background" Value="#f2f2f2" />
            </Trigger>

<Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background" Value="LightGray"/>
                <!--<Setter Property="Foreground" Value="White"/>-->
            </Trigger>

<Trigger Property="IsSelected" Value="True">
                <Setter Property="Foreground" Value="Black"/>
            </Trigger>
        </Style.Triggers>
    </Style>

<!--单元格样式触发-->
    <Style TargetType="DataGridCell">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="DataGridCell">
                    <TextBlock TextAlignment="Center" VerticalAlignment="Center"  >
                           <ContentPresenter />
                    </TextBlock>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True">
                <!--<Setter Property="Background" Value="White"/>
                <Setter Property="BorderThickness" Value="0"/>-->
                <Setter Property="Foreground" Value="Black"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</ResourceDictionary>

问题:当选中时 背景色无法变化,可去掉DataGridCell的代码。但去掉后文本无法垂直居和水平居中了。

解决办法:

在引入样式文件中添加一个风格定义,DataGridCell的每个文本实际是属于TextBlock

<Style x:Key="contentCenterStyle" TargetType="{x:Type TextBlock}">
                <Setter Property="VerticalAlignment" Value="Center" />
            </Style>

然后再XAML的DataGridTextColumn 加入ElementStyle="{StaticResource contentCenterStyle}"

------------------------------------------------------------------------------------------------

附:完美解决在wpf datagrid让列标题居中以及列内容居中

一般我们要实现居中设置 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 中引用ElementStyle

<DataGridTextColumn Header="代码"
            ElementStyle="{StaticResource contentCenterStyle}"
            Binding="{Binding Name}"></DataGridTextColumn>

C# WPF DataGrid 隔行变色及内容居中对齐的更多相关文章

  1. wpf datagrid 隔行变色

    <DataGrid AlternationCount="2"> <DataGrid.RowStyle> <Style TargetType=" ...

  2. easyui datagrid 隔行变色

    easyui datagrid  隔行变色 一:实现样图 二:实现代码 $('#dataGrid').datagrid({ rowStyler:function(index,row){ if (row ...

  3. css3实现左右div高度自适应且内容居中对齐

    主要运用了css3的弹层布局,直接上代码: 效果:左边盒子宽度固定.内容居中对齐.与右侧盒子高度相等,右侧自动缩放 html: <div class="main"> & ...

  4. text-align:justify_内容居中对齐

    一直发现text-align : justify这个对齐方式不好使,都不知道为什么么么哒: 因为两端对齐的这个行的结束要一个有空字符串或者别的不可见的字符,用户代理会把这个行的最后几个字符往右边拉,实 ...

  5. 二、WPF datagrid 行变色

    public void Color(){ DataGridRow row1 = (DataGridRow)this.dgSource.ItemContainerGenerator.ContainerF ...

  6. wpf datagrid 的单元格内容超出列宽度

    ---恢复内容开始--- <Window x:Class="WpfApplication2.MainWindow" xmlns="http://schemas.mi ...

  7. easyui datagrid隔行变色

    属性striped设置为true,即striped:true. 如果想更改颜色,可以更改easyui.css中的.datagrid-row-alt样式.

  8. WPF DataGrid 每行ComboBox 内容不同的设置方法

    <toolkit:DataGridComboBoxColumn x:Name="DgCbcSignal" Header="信号源" SelectedIte ...

  9. WPF DataGrid常用属性记录

    WPF DataGrid常用属性记录 组件常用方法: BeginEdit:使DataGrid进入编辑状态. CancelEdit:取消DataGrid的编辑状态. CollapseRowGroup:闭 ...

随机推荐

  1. Nginx敏感信息泄露漏洞(CVE-2017-7529)

    2017年7月11日,为了修复整数溢出漏洞(CVE-2017-7529), Nginx官方发布了nginx-1.12.1 stable和nginx-1.13.3 mainline版本,并且提供了官方p ...

  2. 【转】Mysql之binlog日志说明及利用binlog日志恢复数据操作记录

    众所周知,binlog日志对于mysql数据库来说是十分重要的.在数据丢失的紧急情况下,我们往往会想到用binlog日志功能进行数据恢复(定时全备份+binlog日志恢复增量数据部分),化险为夷! 废 ...

  3. VCL控件组件大都应该重载TWinControl的虚函数WndProc来进行处理窗口消息的工作

    TWinControl的构造函数中会调用MakeObjectInstance并且传递MainWndProc作为窗口消息处理函数,而MainWndProc则会调用虚函数WndProc来处理窗口消息.留个 ...

  4. 22个所见即所得在线Web编辑器

    这些 Web 编辑器可以在线编辑和处理富 Web 内容,包括格式文本,表格,图片,媒体,链接等等,非常适合集成到 CMS网站内容管理系统中使用.本文又搜集了 22 个 Web 在线编辑器,它们基本代表 ...

  5. linux下查看cpu,内存,硬盘等硬件信息的方法

    说明:Linux下可以在/proc/cpuinfo中看到每个cpu的详细信息.但是对于双核的cpu,在cpuinfo中会看到两个cpu.常常会让人误以为是两个单核的cpu. 一.linux CPU大小 ...

  6. python函数回顾:hex()

    描述 hex() 函数用于将10进制整数转换成16进制,以字符串形式表示. 语法 hex 语法: hex(x) 参数说明: x -- 10进制整数 返回值 返回16进制数,以字符串形式表示. 实例 & ...

  7. Spring Cloud架构

    Spring Cloud主要的组件,以及它的访间流程  1.外部或者内部的非 Spring Cloud目都统一通过API网关(Zuul)来访可内部服务.  2.网关接收到请求后,从注册中心( Eure ...

  8. MySQL中kill所有慢查询进程和锁表进程

    1.kill所有慢查询进程: #!/bin/bash mysql -uroot -pMy_Password -e "show processlist" | grep -i &quo ...

  9. C#加快Bitmap的访问速度

    在对Bitmap图片操作的时候,有时需要用到获取或设置像素颜色方法:GetPixel 和 SetPixel, 如果直接对这两个方法进行操作的话速度很慢,这里我们可以通过把数据提取出来操作,然后操作完在 ...

  10. Python之模块和包(Day21)

    一.Python模块 Python模块(module),是一个Python文件,以.py结尾,包含了Python对象定义和Python语句. 模块让你能够有逻辑的组织你的Python代码段 把相关的代 ...