相信大家在做WPF项目的时候,都会用到Grid这个布局控件,一般情况下,如果只是为了布局,那就不需要显示它的边框,但是也有特殊需求,如果把它当做表格来使用,那就需要为它添加实线边框。下面帖代码:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace WPFStart
{
///
/// 为Grid添加的一个特殊功能,实线边框
///
public class GridHelper
{
//边框的宽度
static double myBorderWidth = 1;
public static double GetBorderWidth(DependencyObject obj)
{
return (double)obj.GetValue(BorderWidthProperty);
}
public static void SetBorderWidth(DependencyObject obj, double value)
{
obj.SetValue(BorderWidthProperty, value);
}
public static readonly DependencyProperty BorderWidthProperty =
DependencyProperty.RegisterAttached("BorderWidth", typeof(double), typeof(GridHelper), new PropertyMetadata(OnBorderWidthChanged));
private static void OnBorderWidthChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
myBorderWidth = (double)e.NewValue;
}
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, DependencyPropertyChangedEventArgs e)
{
var grid = d as Grid;
if ((bool)e.OldValue)
{
grid.Loaded -= (s, arg) => { };
}
if ((bool)e.NewValue)
{
grid.Loaded += (s, arg) =>
{
//根据Grid的顶层子控件的个数去添加边框,同时考虑合并的情况
var controls = grid.Children;
var count = controls.Count;
for (int i = 0; i < count; i++)
{