如何仅在 XAML 中设置上边距? [英] How to set a top margin only in XAML?

查看:25
本文介绍了如何仅在 XAML 中设置上边距?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在代码中单独设置边距,但是如何我是否在 XAML 中执行此操作,例如我该怎么做:

I can set margins individually in code but how do I do it in XAML, e.g. how do I do this:

伪代码:

<StackPanel Margin.Top="{Binding TopMargin}">

推荐答案

关键是要实现这样的代码设置:

The key is to realize that setting it in code like this:

sp2.Margin = new System.Windows.Thickness{ Left = 5 };

相当于:

sp2.Margin = new System.Windows.Thickness{ Left = 5, Top = 0, Right = 0, Bottom = 0 };

不能通过代码或 XAMLThickness 实例中只设置单个值.如果您不设置某些值,它们将隐式为零.因此,您只需执行此操作即可将其他问题中接受的代码示例转换为等效的 XAML:

You can't set just a single value in a Thickness instance through either code or XAML. If you don't set some of the values, they will be implicitly zero. Therefore, you can just do this to convert the accepted code sample in your other question to a XAML equivalent:

<StackPanel Margin="{Binding TopMargin, Converter={StaticResource MyConverter}}"/>

其中 MyConverter 只返回一个 Thickness,它只设置 Top 并将所有其他值保留为零.

where MyConverter just returns a Thickness that sets only the Top and leaves all other values as zero.

当然,您可以编写自己的控件,确实将这些单独的值公开为依赖项属性,以使您的代码更简洁:

Of course, you could write your own control that does expose these individual values as dependency properties to make your code a little cleaner:

<CustomBorder TopMargin="{Binding TopMargin}">
</CustomBorder>

比自定义控件更好的选择是编写附加属性并使用依赖属性设置器中的上述代码更改厚度.以下代码可用于所有具有 Margin 的控件.

A better option than a custom control would be to write an attached property and change the Thickness using the code above in the dependency property setter. The below code would be usable across ALL controls which have a Margin.

public static readonly DependencyProperty TopMarginProperty =
    DependencyProperty.RegisterAttached("TopMargin", typeof(int), typeof(FrameworkElement),
                                        new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender));
public static void SetTopMargin(FrameworkElement element, int value)
{
    // set top margin in element.Margin
}
public static int GetTopMargin(FrameworkElement element)
{
    // get top margin from element.Margin
}

如果您将此与行为结合使用,您可以在 TopMargin 属性上获得通知更改.

If you couple this with a Behavior, you can get notification changes on the TopMargin property.

这篇关于如何仅在 XAML 中设置上边距?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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