添加自定义属性在XAML元素? [英] Adding custom attributes to an element in XAML?
问题描述
在HTML中,没有什么preventing您创建自定义属性,因为它是有效的XML,如
<跨度myProperty的=myvalue的>< / SPAN>
然后就可以读通过JavaScript这个属性。
你可以做WPF中同样的事情?例如:
< myProperty的帆布=myvalue的NAME =MyCanvas的DataContext ={结合}背景=黑保证金=181,0,0,0> < /帆布>
和如果是的话你将如何访问该属性?例如:
MyCanvas.MyProperty;
您可以在附加最接近性能的。基本上,另一类定义了已知的属性(即myProperty的),它可以在其他元件进行设置。
一个例子是在Canvas.Left属性,它用于由画布来定位的子元素。但是,任何类都可以定义一个附加属性。
附加属性背后的关键附加的行为的,这是WPF的一个很大的特点/ Silverlight的。
编辑:
下面是一个例子类:
命名空间myNameSpace对象{
公共静态MyClass类{ 公共静态只读的DependencyProperty MyPropertyProperty = DependencyProperty.RegisterAttached(myProperty的
typeof运算(字符串)的typeof(MyClass的),新FrameworkPropertyMetadata(NULL)); 公共静态字符串GetMyProperty(的UIElement元素){
如果(元素== NULL)
抛出新的ArgumentNullException(元素);
回报(字符串)element.GetValue(MyPropertyProperty);
}
公共静态无效SetMyProperty(的UIElement元素,字符串值){
如果(元素== NULL)
抛出新的ArgumentNullException(元素);
element.SetValue(MyPropertyProperty,值);
}
}
}
然后在XAML中您可以使用它像这样:
的xmlns:地方=CLR的命名空间:myNameSpace对象<帆布地方:MyClass.MyProperty =myvalue的... />
您可以用得到code财产 MyClass.GetMyProperty
并传递该财产设置的元素。
In html, there is nothing preventing you from creating custom attributes, since it is effectively xml such as
<span myProperty="myValue"></span>
Then you can read that property via javascript.
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;
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.
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.
Attached properties are the key behind attached behaviors, which is a great feature of WPF/Silverlight.
EDIT:
Here is an example class:
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);
}
}
}
Then in XAML you can use it like so:
xmlns:local="clr-namespace:MyNamespace"
<Canvas local:MyClass.MyProperty="MyValue" ... />
You can get the property from code using MyClass.GetMyProperty
and passing in the element on which the property is set.
这篇关于添加自定义属性在XAML元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!