您的位置:首页 > 编程语言 > C#

C#(WPF)为Grid添加实线边框

2015-06-15 13:22 567 查看
相信大家在做WPF项目的时候,都会用到Grid这个布局控件,一般情况下,如果只是为了布局,那就不需要显示它的边框,但是也有特殊需求,如果把它当做表格来使用,那就需要为它添加实线边框。下面帖代码:

using System.Windows;

using System.Windows.Controls;

using System.Windows.Media;

namespace WPFStart

{

///

///为Grid添加的一个特殊功能,实线边框

///

public classGridHelper

{

//边框的宽度

static double myBorderWidth = 1;

public static double GetBorderWidth(DependencyObject obj)

{

return (double)obj.GetValue(BorderWidthProperty);

}

public static void SetBorderWidth(DependencyObject obj, doublevalue)

{

obj.SetValue(BorderWidthProperty, value);

}

public static readonly DependencyProperty BorderWidthProperty=

DependencyProperty.RegisterAttached("BorderWidth", typeof(double),typeof(GridHelper), newPropertyMetadata(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, boolvalue)

{

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++)

{

var item = controls[i] as FrameworkElement;

var row = Grid.GetRow(item);

var column = Grid.GetColumn(item);

var rowspan = Grid.GetRowSpan(item);

var columnspan = Grid.GetColumnSpan(item);

//设置边框线的颜色

var border = new Border();

border.BorderBrush = new SolidColorBrush(Colors.White);

if (row == grid.RowDefinitions.Count - 1 && column ==grid.ColumnDefinitions.Count
- 1)

border.BorderThickness = new Thickness(myBorderWidth);

else if (row == grid.RowDefinitions.Count - 1)

border.BorderThickness = new Thickness(myBorderWidth,myBorderWidth, 0, 0);

else if (column == grid.ColumnDefinitions.Count - 1)

border.BorderThickness = new Thickness(myBorderWidth,myBorderWidth, myBorderWidth, 0);

else

border.BorderThickness = new Thickness(myBorderWidth,myBorderWidth,0, 0 );

Grid.SetRow(border, row);

Grid.SetColumn(border, column);

Grid.SetRowSpan(border, rowspan);

Grid.SetColumnSpan(border, columnspan);

grid.Children.Add(border);

}

};

}

}

}

}

在项目中新建这个类,在XAML页面引用设置属性时,需要添加“xmlns:ext="clr-namespace:WPFGrid(项目名称)"“,“ext:GridHelper.ShowBorder="true"”这里就是设置边框是否显示了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: