【问题标题】:Adding custom attributes to an element in XAML?向 XAML 中的元素添加自定义属性?
【发布时间】:2011-08-12 13:50:14
【问题描述】:

在 html 中,没有什么可以阻止您创建自定义属性,因为它实际上是 xml,例如

<span myProperty="myValue"></span>

然后您可以通过 javascript 读取该属性。

你能在 wpf 中做同样的事情吗?例如:

<Canvas MyProperty="MyValue" Name="MyCanvas" DataContext="{Binding}" Background="Black" Margin="181,0,0,0"></Canvas>

如果是这样,您将如何访问该属性?例如:

MyCanvas.MyProperty;

【问题讨论】:

    标签: c# wpf xaml properties


    【解决方案1】:

    你能得到的最接近的是attached properties。基本上,另一个类定义了一个已知属性(即 MyProperty),可以在其他元素上设置。

    Canvas.Left 属性就是一个例子,Canvas 使用它来定位子元素。但是任何类都可以定义附加属性。

    附加属性是 attached behaviors 背后的关键,这是 WPF/Silverlight 的一大特色。

    编辑:

    这是一个示例类:

    namespace MyNamespace {
        public static class MyClass {
    
            public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.RegisterAttached("MyProperty",
                typeof(string), typeof(MyClass), new FrameworkPropertyMetadata(null));
    
            public static string GetMyProperty(UIElement element) {
                if (element == null)
                    throw new ArgumentNullException("element");
                return (string)element.GetValue(MyPropertyProperty);
            }
            public static void SetMyProperty(UIElement element, string value) {
                if (element == null)
                    throw new ArgumentNullException("element");
                element.SetValue(MyPropertyProperty, value);
            }
        }
    }
    

    然后在 XAML 中你可以像这样使用它:

    xmlns:local="clr-namespace:MyNamespace"
    
    <Canvas local:MyClass.MyProperty="MyValue" ... />
    

    您可以使用MyClass.GetMyProperty 从代码中获取属性并传入设置属性的元素。

    【讨论】:

    • 就是这么多,文字。我假设你已经明白了。你有时间制作一个适用于我的小例子的短代码 sn-p 吗?谢谢!
    • @ohmusama - 用一个例子更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 2015-03-09
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多