2012-10-28 30 views
2

我有一個customcontrol項目在CustomControl WPF


static CustomControl1() 
    { 
     DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new  FrameworkPropertyMetadata(typeof(CustomControl1))); 
    } 

    public List<string> MyProperty 
    { 
     get { return (List<string>)GetValue(MyPropertyProperty); } 
     set { SetValue(MyPropertyProperty, value); } 
    } 
    public static readonly DependencyProperty MyPropertyProperty = 
     DependencyProperty.Register("MyProperty", typeof(List<string>), 
                typeof(CustomControl1), 
                new UIPropertyMetadata(new List<string>()));   

當我使用每個myProperty的

一個以上的 CustomControl1在我的應用程序和設定值
<StackPanel HorizontalAlignment="Left" Orientation="Vertical" VerticalAlignment="Top" Width="176"> 
     <local:CustomControl1>   
      <local:CustomControl1.MyProperty> 
       <System:String>A</System:String> 
       <System:String>B</System:String> 
       <System:String>C</System:String> 
       <System:String>D</System:String> 
      </local:CustomControl1.MyProperty>   
     </local:CustomControl1> 
     <local:CustomControl1>   
      <local:CustomControl1.MyProperty> 
       <System:String>F</System:String> 
       <System:String>E</System:String>      
      </local:CustomControl1.MyProperty>   
     </local:CustomControl1> 
    </StackPanel> 

運行解決方案時,每個CustomControl1 和設計模式中顯示的所有值僅顯示上次customcontrol1的值。

因此,看起來他們都共享相同的實例數據。

+0

我想在第一個控件 中設置一個像[A,B,C,D]這樣的列表,並在第二個控件 中設置如[E,F]的列表,但是當運行時,這個控件顯示[A,B,C,D,E,F ] 並在設計模式中只顯示[E,F] ???! –

回答

0

當創建一個集合依賴項屬性(列表,字典...)總是重新初始化DP在類的構造函數。 (否則,你就可以使用所有場合的同一列表)

所以你的情況:

public CustomControl1() 
{ 
    MyProperty = new List<string>(); 
} 

,並在依賴屬性的默認值刪除值:

public static readonly DependencyProperty MyPropertyProperty = 
     DependencyProperty.Register("MyProperty", typeof(List<string>), 
                typeof(CustomControl1), 
                new UIPropertyMetadata(null));