如何仅修改WPF控件的Margin属性的右侧(或左侧,顶部,底部)值? [英] How do I modify ONLY the right (or left, top, bottom) value of a WPF control's Margin property?

查看:504
本文介绍了如何仅修改WPF控件的Margin属性的右侧(或左侧,顶部,底部)值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从代码隐藏中很容易做到这一点:

This is quite easy to do from code-behind:

var button = new Button();
var margin = button.Margin;
margin.Right = 10;
button.Margin = margin;

但是,在XAML中,我仅限于以下内容:

In XAML, however, I'm limited to the following:

<Button Margin="0,0,10,0" />

这样做的问题是,现在我可能通过将其他边距值(即,左,上,下)设置为零来覆盖它们.

The problem with this is that now I've potentially overwritten the other margin values (i.e. left, top, bottom) by setting them to zero).

有什么办法可以使XAML如下所示?

Is there any way to have XAML like the following?

<Button MarginRight="10" />

推荐答案

可以使用附加属性.实际上,这正是附加属性的目的:访问父元素属性或为特定元素添加其他功能.

An attached property could be used. In fact, this is exactly the purpose of attached properties: accessing parent element properties or adding additional functionality to a specific element.

例如,在应用程序中的某个位置定义以下类:

For example, define the following class somewhere in your application:

using System;
using System.Windows;
using System.Windows.Controls;

namespace YourApp.AttachedProperties
{
    public class MoreProps
    {
        public static readonly DependencyProperty MarginRightProperty = DependencyProperty.RegisterAttached(
            "MarginRight",
            typeof(string),
            typeof(MoreProps),
            new UIPropertyMetadata(OnMarginRightPropertyChanged));

        public static string GetMarginRight(FrameworkElement element)
        {
            return (string)element.GetValue(MarginRightProperty);
        }

        public static void SetMarginRight(FrameworkElement element, string value)
        {
            element.SetValue(MarginRightProperty, value);
        }

        private static void OnMarginRightPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            var element = obj as FrameworkElement;

            if (element != null)
            {
                int value;
                if (Int32.TryParse((string)args.NewValue, out value))
                {
                    var margin = element.Margin;
                    margin.Right = value;
                    element.Margin = margin;
                }
            }
        }
    }
}

现在,在XAML中,您所需要做的就是声明以下命名空间:

Now in your XAML all you must do is declare the following namespace:

xmlns:ap="clr-namespace:YourApp.AttachedProperties"

然后您可以编写如下的XAML:

And then you can write XAML such as the following:

<Button ap:MoreProps.MarginRight="10" />


或者,您可以避免使用附加的属性,而编写一些稍长的XAML,例如:

<Button>
    <Button.Margin>
        <Thickness Right="10" />
    </Button.Margin>
</Button>

<Button>
    <Button.Margin>
        <Thickness Right="10" />
    </Button.Margin>
</Button>

这篇关于如何仅修改WPF控件的Margin属性的右侧(或左侧,顶部,底部)值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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