C#WPFDataGrid隔行变色及内容居中对齐

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

dqzww NET学习0

先看效果:

C#WPFDataGrid隔行变色及内容居中对齐

前台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>

更多相关文章
  • 一直发现text-align : justify这个对齐方式不好使,都不知道为什么么么哒: 因为两端对齐的这个行的结束要一个有空字符串或者别的不可见的字符,用户代理会把这个行的最后几个字符往右边拉,实现两端对齐: <!doctype html> <html> <head ...
  • 转自:http://bbs.csdn.net/topics/340170231  昨天在论坛里溜达的时候,发现有同学遇到了居中的问题,页面在 IE 里居中对齐好好的,为什么在其他浏览器里面就不灵了呢?    我曾经也在写一个 JS 日历的时候也被居中弄的焦头烂额,苦不堪言.想必不少人都遇到过这个问题 ...
  • checkbox和后面文字无法居中对齐的解决方案
       制作前端页面时,表单的页面中都存在表单元素与提示文字无法对齐的问题.下面是针对这一问题的解决方案: 先上结果图看效果,吼吼~    最上面两个是经过css处理后的效果,已经居中对齐了哦~,最后一个是没有处理的效果,明显没有对齐.解决的关键是vertical- align:middle属性,一定 ...
  • 支持键盘上下键的隔行变色代码:隔行变色代码非常的常用,尤其是在新闻列表形式的场景,不过大多数都只是支持鼠标效果,而对键盘的上下键并不支持.下面就提供一段支持上下键的隔行变色效果代码.代码如下: ); }) </script> </head> <body> < ...
  •  先说下简单的思路:1.获得窗口的大小,高度,宽度.2.要知道显示的图片(我这里用图片举例)的大小,宽,高.(我的图片显示设置为 宽:960,高600 )3.简单算法,获得的浏览器宽,高 减去 图片的宽,高 除以2 就是 间隔距离了.4.当然还有获得窗口放大,缩小的事件了.根据事件来设置(margi ...
  • 隔行变色表格隔行变色+LI浮动隔行变色
    第一篇文章哈 随便写写表格隔行变色,一个很普通的js效果... 但是我非常不喜欢用table,一是代码累赘,再是...我通常用li写信息列表.例如相册列表,通常是用浮动排版,或者block-inline...一行有好几个li元素这时要隔行变色的话...首先假如总共有7个li,一行有3个li,那最后一 ...
  • vertical-align:sub居然居中对齐了
    vertical-align:sub;居然实现了居中对齐,不解!<!DOCTYPE HTML><html><head><metahttp-equiv="Content-Type"content="text/html; chars ...
  • /*table隔行变色*/    #customers tr {        background:#ffffff;    }         #customers tr:nth-child(2n+1) {            background: #A7C942;        }     ...
一周排行