2011-09-23 42 views
4

我的印象是CLR的依賴屬性包裝在WPF下是可選的,只是在你自己的代碼中設置很有用。依賴屬性的CLR包裝是否可選?

不過,我已經創建無包裝一個用戶控件,但使用它的一些XAML沒它們編譯:

namespace MyControlLib 
{ 
    public partial class MyControl : UserControl 
    { 
     public static readonly DependencyProperty SomethingProperty; 

     static MyControl() 
     { 
      SomethingProperty = DependencyProperty.Register("Something", typeof(int), typeof(MyControl)); 
     } 
    } 
} 

XAML用法:

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:ctrl="clr-namespace:MyControlLib;assembly=MyControlLib"> 

    <ctrl:MyControl Something="45" /> 

</Window> 

嘗試編譯這給:

錯誤MC3072:屬性'Something'不存在於XML名稱空間'clr-namespace:MyControlLib'中。 Line blah位置等等。

添加CLR包裝在MyControl.xaml.cs,如:

public int Something 
{ 
    get { return (int)GetValue(SomethingProperty); } 
    set { SetValue(SomethingProperty, value); } 
} 

意味着它所有的編譯和工作正常。

我錯過了什麼?

回答

4

您可以在運行時綁定內部使用依賴項屬性,而不需要包裝器,但要像您想要的那樣設置屬性,您必須擁有C#屬性以允許xaml編譯器編譯您的代碼。

+1

+1露面,我要補充的是,[CLR「包裝」是執行清單的一部分] (http://msdn.microsoft.com/en-us/library/ms753358.aspx)的依賴項屬性,即使它並不總是由框架使用。 – user7116

1

我相信如果你在屬性上指定了命名空間前綴,它會在沒有包裝的情況下編譯。

它們是可選的,但是沒有他們的財產並不在XAML設計器自動

<ctrl:MyControl ctrl:MyControl.Something="45" /> 
+0

不幸的是,這並不適合我。我得到:錯誤MC3072:屬性'MyControl.Something'不存在於XML命名空間'clr-namespace:MyControlLib – GazTheDestroyer