且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 StackPanel 中设置项目间距的简单方法是什么?

更新时间:2022-06-15 23:07:01

如果所有控件都相同,则按照 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.