2011-04-25 139 views
18

在HTML中,沒有什麼阻止您創建自定義屬性,因爲它實際上是XML如將自定義屬性添加到XAML中的元素?

<span myProperty="myValue"></span> 

然後你就可以通過JavaScript讀取性能。

你可以在wpf中做同樣的事嗎?例如:

<Canvas MyProperty="MyValue" Name="MyCanvas" DataContext="{Binding}" Background="Black" Margin="181,0,0,0"></Canvas> 

如果是這樣,你將如何訪問該屬性?例如:

MyCanvas.MyProperty; 

回答

24

最接近你可以得到的是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得到代碼的性能和傳入設置屬性的元素。

+0

這是很多,文字。我假定你已經明白了。你有沒有時間做一個適用於我的小例子的短代碼片段?謝謝! – ohmusama 2011-04-25 22:24:40

+1

@ohmusama - 用一個例子更新了我的答案。 – CodeNaked 2011-04-25 23:32:43

+1

非常感謝你! – ohmusama 2011-04-25 23:58:12