缘起:经常用Grid的做布局,感觉很好用.
但是当grid的行列数很多时,为了美观,应让其内部控件有相应间距,不至于太挤.
我们需要为其children设置margin属性.
前面提到了grid的行列数很多,一个个设置肯定不是一个程序员喜欢的方式.当然有人提议用Blend,虽然Blend很好用,但是毕竟不是一劳永逸的方式,不喜欢.况且本人的电脑上也没装Blend,而且不会用,O(∩_∩)O~
好了,上代码:
using System.Windows;
using System.Windows.Controls;
namespace CustomControlLibrary
{
public class AutoMarginGrid : Grid
{
public Thickness CellMargin
{
get { return (Thickness)GetValue(CellMarginProperty); }
set { SetValue(CellMarginProperty, value); }
}
// Using a DependencyProperty as the backing store for CellMarginProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty CellMarginProperty =
DependencyProperty.Register("CellMargin", typeof(Thickness), typeof(AutoMarginGrid), new UIPropertyMetadata(new Thickness(5,5,5,5)));
protected override Size MeasureOverride(Size constraint)
{
AddMarginToChild();
return (base.MeasureOverride(constraint));
}
protected override System.Windows.Size ArrangeOverride(System.Windows.Size arrangeSize)
{
return base.ArrangeOverride(arrangeSize);
}
private void AddMarginToChild()
{
foreach (FrameworkElement element in this.Children)
{
element.Margin = this.CellMargin;
}
}
}
}
Xmal中代码:
<CustomCon:AutoMarginGrid CellMargin="10,0,0,0"/>
效果如图:
图1(标准Grid控件,未设置外间距)
图2(AutoMarginGrid 自动设置外间距)