wpf - 如何仅修改WPF控件的Margin属性的右侧(或左侧,顶部,底部)值?

标签 wpf xaml mvvm wpf-controls mvvm-light

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

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

但是,在XAML中,我仅限于以下内容:
<Button Margin="0,0,10,0" />

问题在于,现在我可能通过将其他边距值(即左,上,下)设置为零来覆盖它们。

有什么办法可以使XAML如下所示?
<Button MarginRight="10" />

最佳答案

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

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

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中,您所需要做的就是声明以下 namespace :
xmlns:ap="clr-namespace:YourApp.AttachedProperties"

然后,您可以编写如下的XAML:
<Button ap:MoreProps.MarginRight="10" />



另外,您可以避免使用附加属性,而编写一些稍长的XAML,例如:
<Button><Button.Margin><Thickness Right="10" /></Button.Margin></Button>

关于wpf - 如何仅修改WPF控件的Margin属性的右侧(或左侧,顶部,底部)值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12632079/

相关文章:

wpf - 在运行时 WPF 中设置图像

.net - 当我在 WPF 中使用弹出窗口时出现 COMException

xaml - 分配附加属性值

c# - MVVM 光 5.0 : How to use the Navigation service

c# - 如何将命令绑定(bind)到按钮

c# - 如何处理从另一个 AppDomain 抛出的异常?

c# - 如何获取程序集中定义的 XAML 资源列表?

wpf - 找不到WPF MvxEventToCommand

c# - 在 WPF 应用程序中使用 MVVM 构建数据库优先模型类

ios - 当我需要从两个不同的 Web 服务获取 Controller 数据时,我应该如何使用 MVVM 和依赖注入(inject)?