最接近你可以得到的是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
得到代码的性能和传入设置属性的元素。
这是很多,文字。我假定你已经明白了。你有没有时间做一个适用于我的小例子的短代码片段?谢谢! – ohmusama 2011-04-25 22:24:40
@ohmusama - 用一个例子更新了我的答案。 – CodeNaked 2011-04-25 23:32:43
非常感谢你! – ohmusama 2011-04-25 23:58:12