向 XAML 中的元素添加自定义属性? [英] Adding custom attributes to an element in XAML?
问题描述
在 html 中,没有什么可以阻止您创建自定义属性,因为它实际上是 xml,例如
In html, there is nothing preventing you from creating custom attributes, since it is effectively xml such as
<span myProperty="myValue"></span>
然后您可以通过 javascript 读取该属性.
Then you can read that property via javascript.
你能在 wpf 中做同样的事情吗?例如:
Can you do the same thing in wpf? For example:
<Canvas MyProperty="MyValue" Name="MyCanvas" DataContext="{Binding}" Background="Black" Margin="181,0,0,0"></Canvas>
如果是这样,您将如何访问该属性?例如:
and If so how would you access that property? For example:
MyCanvas.MyProperty;
推荐答案
最接近的是 附加属性.基本上,另一个类定义了一个已知属性(即 MyProperty),该属性可以设置在其他元素上.
The closest you can get are attached properties. Basically, another class defines a known property (i.e. MyProperty), which can be set on other elements.
一个例子是 Canvas.Left 属性,Canvas 使用它来定位子元素.但是任何类都可以定义附加属性.
An example would be the Canvas.Left property, which is used by the Canvas to position a child element. But any class can define an attached property.
附加属性是附加行为背后的关键,这是一个很棒的功能WPF/Silverlight.
Attached properties are the key behind attached behaviors, which is a great feature of 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 中你可以像这样使用它:
Then in XAML you can use it like so:
xmlns:local="clr-namespace:MyNamespace"
<Canvas local:MyClass.MyProperty="MyValue" ... />
您可以使用 MyClass.GetMyProperty
从代码中获取属性,并传入设置属性的元素.
You can get the property from code using MyClass.GetMyProperty
and passing in the element on which the property is set.
这篇关于向 XAML 中的元素添加自定义属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!