开发者

Best way to implement margin between WPF/SL grid columns/rows

What's the best way to add margin between columns or rows in a WPF or Silverlight grid?

  1. Add fixed width/height columns/rows to the grid
  2. Add margin to the grid child controls
  3. Anything else?

Thanks in开发者_如何学Python advance


It depends, really, on your design, and is a matter of your own tastes. The biggest thing is to be consistent.

I think it's perfectly acceptable to put a fixed width "spacer" column or row in most cases - then you don't have to worry about maintenance later (either by you or somebody else).

The thing to watch out for is setting things twice (i.e. both a margin and fixed width column). It's not too big a problem if you are using all the same kind of control, but it could get a little ugly if you use different kinds of controls that have Styles applied to them that include Margins and/or Padding.


If you don't mind deriving your own control from the Grid and using that instead, you can do it quite easily. Since it seems like a good idea I quickly whipped up this (mostly untested and quite ugly!) code:

/// <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;
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜