在WPF / SL网格列/行之间实现边距的最佳方法

时间:2010-10-15 08:52:19

标签: wpf silverlight grid

在WPF或Silverlight网格中的列或行之间添加边距的最佳方法是什么?

  1. 将固定宽度/高度的列/行添加到网格
  2. 为网格子控件添加边距
  3. 还有别的吗?
  4. 提前致谢

2 个答案:

答案 0 :(得分:1)

这取决于你的设计,这取决于你自己的品味。最重要的是要保持一致。

我认为在大多数情况下放置固定宽度的“间隔”列或行是完全可以接受的 - 然后您不必担心以后的维护(无论是您还是其他人)。

需要注意的是设置两次(即边距和固定宽度列)。如果你使用所有相同类型的控件,这不是一个大问题,但是如果你使用不同类型的控件,它们应用了包含边距和/或填充的样式,那么它可能会有点难看。

答案 1 :(得分:0)

如果您不介意从网格中获取自己的控件并使用它,则可以非常轻松地完成。因为这似乎是一个好主意,所以我很快就掀起了这个(大部分未经测试且非常难看!)代码:

/// <summary>
/// Enhanced Grid that can automatically apply a padding to all its children.
/// </summary>
public class PaddedGrid : Grid
{

    /// <summary>
    /// Gets or sets a padding value to apply as the margin to all children.
    /// If left to default (null or 'zero' Thickness) the margins of the children are not modified.
    /// </summary>
    public Thickness? Padding
    {
        get { return (Thickness?)GetValue(PaddingProperty); }
        set { SetValue(PaddingProperty, value); }
    }

    public static readonly DependencyProperty PaddingProperty =
        DependencyProperty.Register("Padding", typeof(Thickness?), typeof(PaddedGrid), new PropertyMetadata(PaddingChanged));

    private bool HasPadding()
    {
        return Padding.HasValue && Padding.Value != default(Thickness);
    }

    private static void PaddingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var g = d as PaddedGrid;
        if (g != null)
        {
            if (!g.HasPadding()) return;
            for (int i = 0; i < g.VisualChildrenCount; i++)
            {
                var v = g.GetVisualChild(i);
                var c = v as FrameworkElement;
                if (c == null || c is GridSplitter) continue;
                c.Margin = (Thickness)e.NewValue;
            }
        }
    }

    protected override void OnVisualChildrenChanged(DependencyObject visualAdded, DependencyObject visualRemoved)
    {
        base.OnVisualChildrenChanged(visualAdded, visualRemoved);
        if (!HasPadding()) return;
        if (visualAdded != null)
        {
            var fe = visualAdded as FrameworkElement;
            if (fe != null) fe.Margin = this.Padding.Value;
        }
    }
}