为WPF的Grid添加边框线

1、定义一个类文件

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace SilverlightApplicationGridBorderSample
{
    /// <summary>
    /// 为Grid添加的一个特殊功能
    /// </summary>
    public class GridHelper
    {

        //请注意:可以通过propa这个快捷方式生成下面三段代码

        public static bool GetShowBorder(DependencyObject obj)
        {
            return (bool)obj.GetValue(ShowBorderProperty);
        }

        public static void SetShowBorder(DependencyObject obj, bool value)
        {
            obj.SetValue(ShowBorderProperty, value);
        }

        public static readonly DependencyProperty ShowBorderProperty =
            DependencyProperty.RegisterAttached("ShowBorder", typeof(bool), typeof(GridHelper), new PropertyMetadata(OnShowBorderChanged));


        //这是一个事件处理程序,需要手工编写,必须是静态方法
        private static void OnShowBorderChanged(DependencyObject d, DNbxnTGymbY6j9EXsAsQAcJdFkMmMoFLAD e)
        {
            var grid = d as Grid;
            if((bool)e.OldValue)
            {
                grid.Loaded -= (s, arg) => { };
            }
            if((bool)e.NewValue)
            {
                grid.Loaded += (s, arg) =>
                {

                    //这种做法自动将控件移动到Border里面来
                    var controls = grid.Children;
                    var count = controls.Count;

                    for(int i = 0; i < count; i++)
                    {
                        var item = controls[i] as FrameworkElement;
                        var border = new Border()
                        {
                            BorderBrush = new SolidColorBrush(Colors.LightGray),
                            BorderThickness = new Thickness(1),
                            Padding = new Thickness(20)
                        };

                        var row = Grid.GetRow(item);
                        var column = Grid.GetColumn(item);
                        var rowspan = Grid.GetRowSpan(item);
                        var columnspan = Grid.GetColumnSpan(item);

                        Grid.SetRow(border, row);
                        Grid.SetColumn(border, column);
                        Grid.SetRowSpan(border, rowspan);
                        Grid.SetColumnSpan(border, columnspan);


                        grid.Children.RemoveAt(i);
                        border.Child = item;
                        grid.Children.Insert(i, border);

                    }
                };
            }

        }

    }

}

2、在XAML文件中增加空间

xmlns:GridLine="clr-namespace:类所在的命名空间"

3、在Grid中引用

将以下属性增加在Grid的属性定义中,像Height等属性的使用一样。

GridLine:GridHelper.ShowBorder="True"

参考链接:https://www.cnblogs.com/chenxizhang/archive/2011/09/22/2185414.html

上一篇:Knight_day3


下一篇:P8086 『JROI-5』Music 题解