最接近你可以得到的是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