在XAML中向元素添加自定义属性?

ohm*_*ama 22 c# wpf xaml properties

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

<span myProperty="myValue"></span>
Run Code Online (Sandbox Code Playgroud)

然后你可以通过javascript阅读该属性.

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

<Canvas MyProperty="MyValue" Name="MyCanvas" DataContext="{Binding}" Background="Black" Margin="181,0,0,0"></Canvas>
Run Code Online (Sandbox Code Playgroud)

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

MyCanvas.MyProperty;
Run Code Online (Sandbox Code Playgroud)

Cod*_*ked 26

您可以获得的最接近的属性.基本上,另一个类定义了一个已知属性(即MyProperty),可以在其他元素上设置.

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

附加属性是附加行为背后的关键,这是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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

xmlns:local="clr-namespace:MyNamespace"

<Canvas local:MyClass.MyProperty="MyValue" ... />
Run Code Online (Sandbox Code Playgroud)

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