在 StackPanel 中设置项目间距的简单方法是什么? [英] What is the easy way to set spacing between items in StackPanel?

查看:31
本文介绍了在 StackPanel 中设置项目间距的简单方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法可以在 StackPanel 内的项目之间设置默认空间,这样我就不必为每个项目设置 Margin 属性?

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?

推荐答案

如果所有控件都相同,则按照 IanR 的建议执行并实现捕获该控件的样式.如果不是,则无法为基类创建默认样式,因为它不起作用.

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.

处理此类情况的最佳方法是使用一个非常巧妙的技巧 - 附加属性(在 WPF4 中也称为行为)

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:

<StackPanel local:MarginSetter.Margin="10">
    <Button Content="hello " />
    <Button Content="hello " />
    <Button Content="hello " />
    <Button Content="hello " />
</StackPanel>

当然可以完全重复使用.

Completely reusable of course.

这篇关于在 StackPanel 中设置项目间距的简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆