用Grid写DataGrid控件

     不少人提到我这篇文章没有demo,现将demo提供如下:demo下载地址  该demo可以直接运行,演示了最基本的数据呈现及合并单元格.

    在ASP.NET中微软官方提供的GridView控件能实现各种样式,如设置字体、背景色、合并单元格等等。这些控件无非都是基本控件的封装,所有样式都是通过控制子控件样式来实现。

    在silverlight中有基本的布局控件Grid、显示数据的TextBlock。有了这些基本控件即可写出能符合各种要求的控件来。

    在编写控件时会遇到如下麻烦:

    1、控件边框问题。Grid本身确实有线,只要将ShowLines设置为true即可,但是这个线却是虚线,不能设置样式。

    2、单元格单击事件问题。Grid中的单元格只有点中内容时才有效,比如单元格比较大就一个字的情况,只有点中这个字时才能触发事件。

    3、合并单元格问题。合并单元格的思路是先将被合并的单元格内容清楚,再将合并的内容扩展,思路比较清晰但实现上可能会遇到麻烦。

    重新分析设计思路,其实这些问题并不难解决。

    1、边框问题,那可以用一个Rectangle来顶替。但因为每个单元格都有边框,且合并但远格时边框也要随着伸缩。于是可以考虑动态画这个Rectangle,创建一个单元格就画一个Rectangle.其中代码如下:

public void DrawRectangle(Color lineColor)
        {
            Rectangle r = new Rectangle();
            r.Stroke = new SolidColorBrush(lineColor);
            //r.Fill = backGround;
            r.StrokeThickness = lineBord;
            //r.Stretch = Stretch.Fill;
            //Canvas.SetZIndex(r, -1);
            r.Margin = new Thickness(0, 0, -1, -1);
            if ((Y == columnCount - 1) && (columnCount != 0))
            {
                r.Margin = new Thickness(0, 0, 0, -1);
            }
            this.LayoutRoot.Children.Add(r);

            //CellRectangle = r;
        }

这个方法是公有方法,是在声明单元格后调用的。

    2、单元格单击事件问题就可以想方设法让单元格内容完全填充Grid的整个单元格,于是可以将每个单元格看做是一个独立的子控件,也就是说先封装一个单元格控件,该控件能设置各种样式,如背景色、字体大小、还能当模板用。 该单元格控件名称为:   SimpleDataGridCell

    3、合并单元格的思路很简单,但是难点是怎么找到这个单元格,考虑到每个单元格都是一个独立的自定义控件,故而可以给这个单元格设置两个坐标属性X和Y,然后在Grid中查找该坐标的单元格即可,同时合并单元格的属性应该放在单元格中才行,但实现单元格的合并是在调用单元格的主控件中实现,这时可以用事件来解决这个问题。即在单元格中声明两个事件。

/// <summary>
        /// 合并行
        /// </summary>
        public event Action<SimpleDataGridCell> SetRowSpanEvent;

        /// <summary>
        /// 合并列
        /// </summary>
        public event Action<SimpleDataGridCell> SetColumnSpanEvent;

在设置合并单元格时进行调用

public int ColumnSpan
        {
            get { return columnSpan; }
            set
            {
                columnSpan = value;
                if (SetColumnSpanEvent != null)
                {
                    SetColumnSpanEvent(this);
                }
            }
        }

        public int RowSpan
        {
            get { return rowSpan; }
            set
            {
                rowSpan = value;
                if (SetRowSpanEvent != null)
                {
                    SetRowSpanEvent(this);
                }
            }
        }

在声明单元格时注册这两个事件

    cell.SetRowSpanEvent += new Action<SimpleDataGridCell>(cell_SetRowSpanEvent);
    cell.SetColumnSpanEvent += new Action<SimpleDataGridCell>(cell_SetColumnSpanEvent);
这些问题都解决了那其他都迎刃而解。下面是整个控件的源码:

单元格的设计界面: SimpleDataGridCell.xaml
<UserControl x:Class="PAS.PerfCmcc.SimpleDataGrid.SimpleDataGridCell"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" MouseLeftButtonUp="UserControl_MouseLeftButtonUp" MouseRightButtonUp="UserControl_MouseRightButtonUp" MouseEnter="UserControl_MouseEnter">
    
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <ContentPresenter x:Name="cpContent" Canvas.ZIndex="99"></ContentPresenter>
    </Grid>
</UserControl>
C#代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace PAS.PerfCmcc.SimpleDataGrid
{
    public partial class SimpleDataGridCell : UserControl
    {
        public SimpleDataGridCell()
        {
            InitializeComponent();
            this.LayoutRoot.Loaded += new RoutedEventHandler(LayoutRoot_Loaded);

            this.MouseEnter += new MouseEventHandler(SimpleDataGridCell_MouseEnter);
            this.MouseLeave += new MouseEventHandler(SimpleDataGridCell_MouseLeave);

            Rectangle.IsHitTestVisible = false;
            Rectangle.Fill = new SolidColorBrush(Color.FromArgb(0x22, 0x00, 0x00, 0x00));
            Rectangle.StrokeThickness = 1;
            Rectangle.Stroke = new SolidColorBrush(Colors.LightGray);
            Rectangle.RadiusX = 2;
            Rectangle.RadiusY = 2;
            Rectangle.Margin = new Thickness(1);
            Rectangle.Visibility = System.Windows.Visibility.Collapsed;
            this.LayoutRoot.Children.Add(Rectangle);
        }

        private Rectangle Rectangle = new Rectangle();
        void SimpleDataGridCell_MouseLeave(object sender, MouseEventArgs e)
        {
            Rectangle.Visibility = System.Windows.Visibility.Collapsed;
        }

        void SimpleDataGridCell_MouseEnter(object sender, MouseEventArgs e)
        {
            Rectangle.Visibility = System.Windows.Visibility.Visible;
        }

        void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
        {
            InitControls();
        }

        #region 私有字段
        private Brush backGround = new SolidColorBrush(Colors.White);
        private Brush columnBackground = new SolidColorBrush(Colors.White);
        private Brush headerBackground = new SolidColorBrush(Colors.White);
        private Color foreColor = Colors.Black;
        private int columnSpan = 1;
        private int rowSpan = 1;
        private Object content = new TextBlock() { Text="显示数据"};
        private HorizontalAlignment hAlign = HorizontalAlignment.Center;
        private VerticalAlignment vAlign = VerticalAlignment.Center;
        private Rectangle rectangle;
        private double lineBord = 1;
        #endregion

        #region 单元格属性

        public int X { get; set; }
        public int Y { get; set; }
        public int rowCount { get; set; }
        public int columnCount { get; set; }

        /// <summary>
        /// 表头样式
        /// </summary>
        public Brush HeaderBackground
        {
            get { return this.headerBackground; }
            set
            {
                headerBackground = value;
                this.Background = value;
            }
        }

        /// <summary>
        /// 一列的背景色
        /// </summary>
        public Brush ColumnBackground
        {
            get { return this.columnBackground; }
            set
            {
                columnBackground = value;
                this.Background = value;
            }
        }

        [DefaultValue("1"),Description("边框宽度"),Category("Appearance")]
        public double LineBord
        {
            get { return lineBord; }
            set { lineBord = value; }
        }

        public static new DependencyProperty BackgroundProperty =
            DependencyProperty.Register("Background",typeof(Brush),typeof(SimpleDataGridCell),null);
        public new Brush Background
        {
            //get { return backGround; }
            get { return (Brush)GetValue(BackgroundProperty); }
            set
            {
                backGround = value;
                SetValue(BackgroundProperty, value);
                this.LayoutRoot.Background = value;
            }
        }

        public static DependencyProperty ForeColorProperty =
            DependencyProperty.Register("ForeColor", typeof(Color), typeof(SimpleDataGridCell),null);
        public Color ForeColor
        {
            get { return foreColor; }
            set
            {
                foreColor = value;
                this.Foreground = new SolidColorBrush(foreColor);
            }
        }

        public int ColumnSpan
        {
            get { return columnSpan; }
            set
            {
                columnSpan = value;
                if (SetColumnSpanEvent != null)
                {
                    SetColumnSpanEvent(this);
                }
            }
        }

        public int RowSpan
        {
            get { return rowSpan; }
            set
            {
                rowSpan = value;
                if (SetRowSpanEvent != null)
                {
                    SetRowSpanEvent(this);
                }
            }
        }

        public new Object Content
        {
            get { return content; }
            set
            {
                content = value;
                this.cpContent.Content = content;
            }
        }

        public new Object Tag { get; set; }

        public new HorizontalAlignment HorizontalAlignment
        {
            get { return hAlign; }
            set
            {
                hAlign = value;
                this.cpContent.HorizontalAlignment = hAlign;
            }
        }

        public new VerticalAlignment VerticalAlignment
        {
            get { return vAlign; }
            set
            {
                vAlign = value;
                this.cpContent.VerticalAlignment = vAlign;
            }
        }

        public Rectangle CellRectangle
        {
            get { return rectangle; }
            set
            {
                rectangle = value;
                if (rectangle != null)
                {
                    rectangle.Margin = new Thickness(0, 0, -1, -1);
                    this.LayoutRoot.Children.Add(rectangle);
                }
            }
        }
        #endregion

        public void DrawRectangle(Color lineColor)
        {
            Rectangle r = new Rectangle();
            r.Stroke = new SolidColorBrush(lineColor);
            //r.Fill = backGround;
            r.StrokeThickness = lineBord;
            //r.Stretch = Stretch.Fill;
            //Canvas.SetZIndex(r, -1);
            r.Margin = new Thickness(0, 0, -1, -1);
            if ((Y == columnCount - 1) && (columnCount != 0))
            {
                r.Margin = new Thickness(0, 0, 0, -1);
            }
            this.LayoutRoot.Children.Add(r);

            //CellRectangle = r;
        }

        private void InitControls()
        {
            this.cpContent.VerticalAlignment = vAlign;
            this.cpContent.HorizontalAlignment = hAlign;
        }

        /// <summary>
        /// 合并行
        /// </summary>
        public event Action<SimpleDataGridCell> SetRowSpanEvent;

        /// <summary>
        /// 合并列
        /// </summary>
        public event Action<SimpleDataGridCell> SetColumnSpanEvent;

        /// <summary>
        /// 单击单元格事件
        /// </summary>
        public event Action<SimpleDataGridCell> CellClick;

        /// <summary>
        /// 右键单元格事件
        /// </summary>
        public event Action<SimpleDataGridCell> CellRightMouseClick;

        private void UserControl_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            SimpleDataGridCell gridCell = sender as SimpleDataGridCell;
            if (CellClick != null)
            {
                CellClick(gridCell);
            }
        }

        private void UserControl_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            SimpleDataGridCell gridCell = sender as SimpleDataGridCell;
            if (CellRightMouseClick != null)
            {
                CellRightMouseClick(gridCell);
            }
        }

        private void UserControl_MouseEnter(object sender, MouseEventArgs e)
        {

        }
    }
}

 

主界面: SimpleDataGrid.xaml

 

<UserControl x:Class="PAS.PerfCmcc.SimpleDataGrid.SimpleDataGrid"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    
    <Grid x:Name="LayoutRoot" Background="White">
        <Border BorderBrush="Black" BorderThickness="0" x:Name="gridBord">
            <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"> 
                <Grid Name="NewGrid" MouseLeftButtonUp="NewGrid_MouseLeftButtonUp" MouseRightButtonUp="NewGrid_MouseRightButtonUp"></Grid>
            </ScrollViewer>
        </Border>
    </Grid>
</UserControl>

 

实现代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Runtime.Serialization.Json;
using System.IO;
using System.ComponentModel;

namespace PAS.PerfCmcc.SimpleDataGrid
{
    public partial class SimpleDataGrid : UserControl
    {
        SimpleDataGridCell sdCell = new SimpleDataGridCell();
        public SimpleDataGrid()
        {
            InitializeComponent();
            this.LayoutRoot.Loaded += new RoutedEventHandler(LayoutRoot_Loaded);
        }

        public Brush DefaultCellBackground { get; set; }

        void sdCell_SetRowSpanEvent(SimpleDataGridCell obj)
        {
            foreach (SimpleDataGridCell child in this.NewGrid.Children)
            {
                if (child == null) continue;

                int rowIndex = (int)child.GetValue(Grid.RowProperty);
                int colIndex = (int)child.GetValue(Grid.ColumnProperty);

                if (rowIndex == child.X && child.Y == colIndex)
                {
                    int rowSpan = child.RowSpan;
                    int meil = rowSpan - 1;
                    for (int i = 0; i < meil; i++)
                    {
                        SimpleDataGridCell ch = GetCell(i + rowIndex, colIndex);
                        ch = null;
                    }
                    Grid.SetRowSpan(child, rowSpan);
                }
            }
        }

        void sdCell_SetColumnSpanEvent(SimpleDataGridCell obj)
        {
            foreach (SimpleDataGridCell child in this.NewGrid.Children)
            {
                if (child == null) continue;

                int rowIndex = (int)child.GetValue(Grid.RowProperty);
                int colIndex = (int)child.GetValue(Grid.ColumnProperty);

                if (rowIndex == child.X && child.Y == colIndex)
                {
                    int colSpan = child.ColumnSpan;
                    int meil = colSpan - 1;
                    for (int i = 0; i < meil; i++)
                    {
                        SimpleDataGridCell ch = GetCell(rowIndex, colIndex + i);
                        ch = null;
                    }
                    Grid.SetRowSpan(child, colSpan);
                }
            }
        }

        void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
        {
            //InitTable();
        }

        private int tempX = 0;
        private int tempY = 0;
        #region 控件字段
        private Brush backGround = new SolidColorBrush(Colors.White);
        private Brush columnBackground = new SolidColorBrush(Colors.White);
        private Brush headerBackground = new SolidColorBrush(Colors.White);
        private string columnGroup = "0";
        private int[] columnGroups = new int[] { 0 };
        private int defaultRowHeight = 28;
        private int rowCount = 3;
        private int columnCount = 3;
        private double lineBord = 1;
        private Color lineColor = Colors.Black;
        private Color foreColor = Colors.Black;
        private Object dataSource;
        #endregion

        #region 控件属性

        public static new DependencyProperty BackgroundProperty =
            DependencyProperty.Register("Background", typeof(Brush), typeof(SimpleDataGrid), null);
        public new Brush Background
        {
            //get { return backGround; }
            get { return (Brush)GetValue(BackgroundProperty); }
            set
            {
                backGround = value;
                SetValue(BackgroundProperty, value);
            }
        }

        /// <summary>
        /// 表头样式
        /// </summary>
        public static DependencyProperty HeaderBackgroundProperty =
            DependencyProperty.Register("HeaderBackground", typeof(Brush), typeof(SimpleDataGrid), null);
        [Browsable(true)]
        [DefaultValue("1"), Description("表头颜色"), Category("HeaderStyle")]
        public Brush HeaderBackground
        {
            get { return (Brush)GetValue(HeaderBackgroundProperty); }
            set
            {
                headerBackground = value;
                SetValue(HeaderBackgroundProperty, value);
            }
        }

        /// <summary>
        /// 一列的背景色
        /// </summary>
        public static DependencyProperty ColumnBackgroundProperty =
            DependencyProperty.Register("ColumnBackground", typeof(Brush), typeof(SimpleDataGrid), null);
        [Browsable(true)]
        [DefaultValue("1"), Description("列颜色"), Category("ColumnStyle")]
        public Brush ColumnBackground
        {
            get { return (Brush)GetValue(ColumnBackgroundProperty); }
            set
            {
                columnBackground = value;
                SetValue(ColumnBackgroundProperty, value);
            }
        }

        public static DependencyProperty ColumnGroupsProperty =
            DependencyProperty.Register("ColumnGroup", typeof(string), typeof(SimpleDataGrid), null);
        [Browsable(true)]
        [DefaultValue("0"), Description("需要变换颜色的列"), Category("ColumnStyle")]
        public string ColumnGroups
        {
            get { return (string)GetValue(ColumnGroupsProperty); }
            set
            {
                this.columnGroup = value;
                SetValue(ColumnGroupsProperty, value);
                string[] temp = columnGroup.Split(',');
                int len = temp.Length;
                columnGroups = new int[len];
                for (int i = 0; i < len; i++)
                {
                    columnGroups[i] = Convert.ToInt32(temp[i]);
                }
            }
        }

        public static DependencyProperty ForeColorProperty =
            DependencyProperty.Register("ForeColor", typeof(Color), typeof(SimpleDataGrid), null);
        public Color ForeColor
        {
            get { return (Color)GetValue(ForeColorProperty); }
            set
            {
                foreColor = value;
                SetValue(ForeColorProperty, value);
            }
        }

        [Browsable(true)]
        [DefaultValue("1"),Description("边框宽度"),Category("Appearance")]
        public double LineBord
        {
            get { return lineBord; }
            set { lineBord = value; }
        }

        /// <summary>
        /// 默认行高
        /// </summary>
        public int DefaultRowHeight
        {
            get { return defaultRowHeight; }
            set { defaultRowHeight = value; }
        }

        /// <summary>
        /// 默认行数
        /// </summary>
        public int RowCount
        {
            get { return rowCount; }
            set
            {
                rowCount = value;
                setRowCount(rowCount);
            }
        }

        /// <summary>
        /// 默认列数
        /// </summary>
        public int ColumnCount
        {
            get { return columnCount; }
            set
            {
                columnCount = value;
                setColCount(columnCount);
            }
        }

        /// <summary>
        /// 边框颜色
        /// </summary>

        public static DependencyProperty LineColorProperty =
            DependencyProperty.Register("LineColor",typeof(Color),typeof(SimpleDataGrid),null);
        [Browsable(true)]
        [DefaultValue("#FFFFFF"),Description("边框颜色"),Category("Appearance")]
        public Color LineColor
        {
            //get { return lineColor; }
            get { return (Color)GetValue(LineColorProperty); }
            set
            {
                SetValue(LineColorProperty, value);
                lineColor = value;
                ChangeBorderColor();
            }
        }

        /// <summary>
        /// 数据源
        /// </summary>
        public Object DataSource
        {
            get { return dataSource; }
            set { dataSource = value; }
        }
        #endregion

        public void Load()
        {
            //InitTable();
        }

        /// <summary>
        /// 设置行数
        /// </summary>
        /// <param name="count"></param>
        private void setRowCount(int count)
        {
            this.NewGrid.RowDefinitions.Clear();
            for (int i = 0; i < count; i++)
            {
                RowDefinition row = new RowDefinition();
                row.Height = new GridLength(defaultRowHeight);
                NewGrid.RowDefinitions.Add(row);
            }
            SetGridStyle();
            InitGridByEmptyCell(count, columnCount);
        }

        /// <summary>
        /// 设置列数
        /// </summary>
        /// <param name="count"></param>
        private void setColCount(int count)
        {
            this.NewGrid.ColumnDefinitions.Clear();
            for (int i = 0; i < count; i++)
            {
                ColumnDefinition col = new ColumnDefinition();
                this.NewGrid.ColumnDefinitions.Add(col);
            }
            SetGridStyle();
            InitGridByEmptyCell(rowCount,count);
        }

        /// <summary>
        /// 设置边框颜色
        /// </summary>
        private void setLineColor()
        {
            
        }

        private void SetTableHeight()
        {
            this.NewGrid.Height = rowCount * defaultRowHeight;
            this.gridBord.Height = this.NewGrid.Height;
        }

        private void InitTable()
        {
            setColCount(columnCount);
            setRowCount(rowCount);
            //SetTableHeight();
            InitContent();
        }

        private void InitContent()
        {
            this.NewGrid.Children.Clear();
            for (int i = 0; i < rowCount; i++)
            {
                for (int j = 0; j < columnCount; j++)
                {
                    tempX = i;
                    tempY = j;
                    //DrawRectangle(i, j);
                    SimpleDataGridCell cell = new SimpleDataGridCell();
                    if (DefaultCellBackground != null)
                        cell.Background = DefaultCellBackground;

                    cell.X = i;
                    cell.Y = j;
                    cell.ColumnSpan = 1;
                    cell.RowSpan = 1;
                    TextBlock tb = new TextBlock();
                    tb.Text = "test";
                    cell.Content = tb;
                    cell.ForeColor = Colors.Black;
                    // cell.Background = new SolidColorBrush(Colors.White);
                    cell.HorizontalAlignment = HorizontalAlignment.Center;
                    if (i == 1 && j == 1)
                    {
                        cell.ColumnSpan = 2;
                        j++;
                    }
                    cell.DrawRectangle(lineColor);
                    this.NewGrid.Children.Add(cell);
                    Grid.SetColumn(cell, tempY);
                    Grid.SetRow(cell, tempX);
                    Grid.SetRowSpan(cell, cell.RowSpan);
                    Grid.SetColumnSpan(cell, cell.ColumnSpan);
                }
            }
        }

        /// <summary>
        /// 改变边框颜色
        /// </summary>
        private void ChangeBorderColor()
        {
            for (int i = 0; i < rowCount; i++)
            {
                for (int j = 0; j < columnCount; j++)
                {
                    SimpleDataGridCell cell = GetCell(i,j);
                    if (cell != null)
                    {
                        cell.DrawRectangle(lineColor);
                    }
                }
            }
        }

        /// <summary>
        /// 初始化表格内容
        /// </summary>
        /// <param name="row"></param>
        /// <param name="col"></param>
        private void InitGridByEmptyCell(int row,int col)
        {
            this.NewGrid.Children.Clear();
            for (int i = 0; i < row; i++)
            {
                for (int j = 0; j < col; j++)
                {
                    tempX = i;
                    tempY = j;
                    SimpleDataGridCell cell = new SimpleDataGridCell();
                    if (DefaultCellBackground != null)
                        cell.Background = DefaultCellBackground;

                    cell.SetRowSpanEvent += new Action<SimpleDataGridCell>(cell_SetRowSpanEvent);
                    cell.SetColumnSpanEvent += new Action<SimpleDataGridCell>(cell_SetColumnSpanEvent);
                    cell.rowCount = rowCount;
                    cell.columnCount = columnCount;
                    cell.X = i;
                    cell.Y = j;
                    //背景色的填充顺序:先填充背景色、再填充列背景色、最后填充表头颜色。一般情况如果是列背景色则需要先填充背景色在填充列背景色
                    //如果是表头背景色则先填充背景色再填充表头背景色
                    if (((SolidColorBrush)this.backGround).Color.ToString() != Colors.White.ToString())
                    {
                        cell.Background = this.backGround;//背景色
                    }
                    if (((SolidColorBrush)this.columnBackground).Color.ToString() != (Colors.White).ToString())
                    {
                        int cLen = columnGroups.Length;
                        for (int t = 0; t < cLen; t++)
                        {
                            if (i != 0 && j == columnGroups[t])
                            {
                                cell.ColumnBackground = this.columnBackground;//列背景色
                            }
                        }
                    }
                    if (((SolidColorBrush)this.headerBackground).Color.ToString() != (Colors.White).ToString())
                    {
                        if (i == 0)
                        {
                            cell.HeaderBackground = this.headerBackground;//表头背景色
                        }
                    }

                    if (this.foreColor.ToString() != (Colors.Black).ToString())
                    {
                        cell.ForeColor = this.foreColor;
                    }
                    //cell.ColumnSpan = 1;
                    //cell.RowSpan = 1;
                    cell.DrawRectangle(lineColor);
                    this.NewGrid.Children.Add(cell);
                    Grid.SetColumn(cell, tempY);
                    Grid.SetRow(cell, tempX);
                    //Grid.SetRowSpan(cell, cell.RowSpan);
                    //Grid.SetColumnSpan(cell, cell.ColumnSpan);
                }
            }
        }

        void cell_SetColumnSpanEvent(SimpleDataGridCell obj)
        {
            foreach (SimpleDataGridCell child in this.NewGrid.Children)
            {
                if (child == null) continue;

                int rowIndex = (int)child.GetValue(Grid.RowProperty);
                int colIndex = (int)child.GetValue(Grid.ColumnProperty);

                if (rowIndex == obj.X && obj.Y == colIndex)
                {
                    int colSpan = child.ColumnSpan;
                    int meil = colSpan - 1;
                    for (int i = 0; i < meil; i++)
                    {
                        SimpleDataGridCell ch = GetCell(rowIndex, colIndex + i + 1);
                        if (ch == null) continue;

                        ch.LayoutRoot.Children.Clear();
                        ch.Background = new SolidColorBrush(Colors.Transparent);
                        ch = null;
                    }
                    Grid.SetColumnSpan(child, colSpan);
                }
            }
        }

        void cell_SetRowSpanEvent(SimpleDataGridCell obj)
        {
            foreach (SimpleDataGridCell child in this.NewGrid.Children)
            {
                if (child == null) continue;

                int rowIndex = (int)child.GetValue(Grid.RowProperty);
                int colIndex = (int)child.GetValue(Grid.ColumnProperty);

                if (rowIndex == obj.X && obj.Y == colIndex)
                {
                    int rowSpan = child.RowSpan;
                    int meil = rowSpan - 1;
                    for (int i = 0; i < meil; i++)
                    {
                        SimpleDataGridCell ch = GetCell(i + rowIndex + 1, colIndex);

                        if (ch == null) continue;

                        ch.LayoutRoot.Children.Clear();
                        ch.Background = new SolidColorBrush(Colors.Transparent);
                        ch = null;
                    }
                    Grid.SetRowSpan(child, rowSpan);
                }
            }
        }

        private void DrawRectangle(int row, int col)
        {
            Rectangle r = new Rectangle();
            r.Stroke = new SolidColorBrush(lineColor);
            r.StrokeThickness = 0.5;
            r.Stretch = Stretch.Fill;
            this.NewGrid.Children.Add(r);
            Grid.SetRow(r, row);
            Grid.SetColumn(r, col);
        }

        public SimpleDataGridCell GetCell(int row, int col)
        {
            foreach (SimpleDataGridCell child in this.NewGrid.Children)
            {
                if (child == null) continue;
                
                int rowIndex = (int)child.GetValue(Grid.RowProperty);
                int colIndex = (int)child.GetValue(Grid.ColumnProperty);

                if (rowIndex == row && col == colIndex)
                    return child;
            }
            return null;
        }

        /// <summary>
        /// 设置行高
        /// </summary>
        /// <param name="row"></param>
        /// <param name="height"></param>
        public void SetRowHeight(int row, int height)
        {
            NewGrid.RowDefinitions[row].Height = new GridLength(height);
            for (int i = 0; i < columnCount; i++)
            {
                SimpleDataGridCell cell = GetCell(row, i);
                if (cell != null)
                {
                    if (height == 0)
                    {
                        cell.Visibility = Visibility.Collapsed;
                    }
                    else
                    {
                        cell.Visibility = Visibility.Visible;
                    }
                }
            }
        }

        /// <summary>
        /// 设置列宽
        /// </summary>
        /// <param name="col"></param>
        /// <param name="width"></param>
        public void SetColumnWidth(int col, int width)
        {
            NewGrid.ColumnDefinitions[col].Width = new GridLength(width);
            for (int i = 0; i < columnCount; i++)
            {
                SimpleDataGridCell cell = GetCell(i, col);
                if (cell != null)
                {
                    if (width == 0)
                    {
                        cell.Visibility = Visibility.Collapsed;
                    }
                    else
                    {
                        cell.Visibility = Visibility.Visible;
                    }

                    if (cell.ColumnSpan > 1)
                    {
                        cell_SetColumnSpanEvent(cell);
                    }
                }
            }
        }

        public void SetGridStyle()
        {
            //边框颜色
            Style style = Application.Current.Resources["SimpleGridStyle"] as Style;
            this.Style = style;

            //边框颜色
            Color lcolor = (Color)this.GetValue(SimpleDataGrid.LineColorProperty);
            this.LineColor = lcolor;

            //前景色
            lcolor = (Color)this.GetValue(SimpleDataGrid.ForeColorProperty);
            this.foreColor = lcolor;

            //表头背景颜色
            Brush brush = (Brush)this.GetValue(SimpleDataGrid.HeaderBackgroundProperty);
            this.headerBackground = brush;

            //背景颜色
            brush = (Brush)this.GetValue(SimpleDataGrid.BackgroundProperty);
            this.backGround = brush;

            //指定列背景颜色
            brush = (Brush)this.GetValue(SimpleDataGrid.ColumnBackgroundProperty);
            this.columnBackground = brush;

            //制定的列
            string group = (string)this.GetValue(SimpleDataGrid.ColumnGroupsProperty);
            this.ColumnGroups = group;
        }

        private void NewGrid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            
        }

        private void NewGrid_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {

        }
    }
}


到此即写完整个GridView控件,经过测试,能实现各种样式,基本达到预期效果!



评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值