What is the easy way to set spacing between items in StackPanel?

后端 未结 4 792
情书的邮戳
情书的邮戳 2021-02-01 05:50

Is there an easy way to set default space between items inside StackPanel so I\'ll don\'t have to set Margin property on each item?

4条回答
  •  后悔当初
    2021-02-01 06:10

    if all the controls are the same then do as IanR suggested and implement a Style that catches that control. if it's not then you can't create a default style to a base class because it just won't work.

    the best way for situations like these is to use a very neat trick - attached properties (aka Behaviors in WPF4)

    you can create a class that has an attached property, like so:

    public class MarginSetter
    {
        public static Thickness GetMargin(DependencyObject obj)
        {
            return (Thickness)obj.GetValue(MarginProperty);
        }
    
        public static void SetMargin(DependencyObject obj, Thickness value)
        {
            obj.SetValue(MarginProperty, value);
        }
    
        // Using a DependencyProperty as the backing store for Margin.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty MarginProperty =
            DependencyProperty.RegisterAttached("Margin", typeof(Thickness), typeof(MarginSetter), new UIPropertyMetadata(new Thickness(), CreateThicknesForChildren));
    
        public static void CreateThicknesForChildren(object sender, DependencyPropertyChangedEventArgs e)
        {
            var panel = sender as Panel;
    
            if (panel == null) return;
    
            foreach (var child in panel.Children)
            {
                var fe = child as FrameworkElement;
    
                if (fe == null) continue;
    
                fe.Margin = MarginSetter.GetMargin(panel);
            }
        }
    
    
    }
    

    now, to use it, all you need to do is to attach this attached property to any panel you want, like so:

    
        

    Completely reusable of course.

提交回复
热议问题