2013-11-03 87 views
2

我已經創建了兩個自定義控件。 1. LeafControl 2- LeafItemControl。 在LeafControl中,我創建了一個類型爲「List」的Dependency屬性作爲「Items」。自定義控件依賴項屬性集合,統計嵌套控件項目

  • 另外在LeafItemControl中,我公開了一個類型爲ContentControl的更多依賴項屬性調用「ItemDetails」。

    <!---Base Custom Control "LeafControl"--> 
    


     <uc:LeafControlItem.ItemDetails> <!--"ItemDetails" is a Dependency Property of type "LeafControl" in "LeafControlItem" custom control --> 
         <uc:LeafControl> <!--Nested Control of same type ???--> 
         <uc:LeafControl.Items> 
         <uc:LeafControlItem Level="Some Type"> 
          <uc:LeafControlItem.ItemContent> 
           <GroupBox BorderThickness="0"> 
            <StackPanel Orientation="Horizontal"> 
            <TextBox Text="Property"></TextBox> 
            </StackPanel> 
           </GroupBox> 
          </uc:LeafControlItem.ItemContent> 
    
          </uc:LeafControlItem> 
          <uc:LeafControlItem Level="Variable"> 
           <uc:LeafControlItem.ItemContent> 
                <GroupBox BorderThickness="0"> 
                 <StackPanel Orientation="Horizontal"> 
                  <TextBox Text="Ellipse2.Top"></TextBox> 
                 </StackPanel> 
                </GroupBox> 
               </uc:LeafControlItem.ItemContent> 
              </uc:LeafControlItem> 
             </uc:LeafControl.Items> 
            </uc:LeafControl> 
           </uc:LeafControlItem.ItemDetails> 
          </uc:LeafControlItem> 
    

當我嘗試訪問基本自定義控件中的「項目」時。所有的孩子自定義控件都增加了爲什麼?我應該怎麼做,以便每個自定義控件對象(基礎和兒童)都有單獨的「項目」。

我已經使用依賴項屬性在基本自定義控件這樣的:

#region LeafControlItemCollection 

     public List<LeafControlItem> Items 
     { 
      get { return (List<LeafControlItem>)GetValue(ItemsProperty); } 
      set { SetValue(ItemsProperty, value); } 
     } 

     public static readonly DependencyProperty ItemsProperty = 
      DependencyProperty.Register(
       "Items", typeof(List<LeafControlItem>), typeof(LeafControl), 
       new FrameworkPropertyMetadata(new List<LeafControlItem>(), null, null) 
      ); 
#endregion 

請建議我在哪裏做錯了。

+0

我的答案適合您嗎? –

+1

嗨,謝謝!那工作。我還發現了另一種方法。將「Items」依賴項屬性數據類型暴露爲「ItemsControl」。在xaml中,我可以像其他itemscontrol一樣將Items添加到它。它也可以正常工作。 – user2565258

回答

3

問題出現在依賴屬性標識符的聲明中,即ItemsProperty。您已提供default value as new List<LeafControlItem>()。通過這樣做,您創建了一個下的包裝。

把它讀出來here,它描述了與列表DP的默認初始化相同的問題。從這個鏈接引用 -

如果你的財產是引用類型,在 依賴項屬性的元數據中指定的默認值是不是每個實例的默認值; 而是它是一個默認值,適用於 類型的所有實例。因此,您必須小心不要將集合屬性元數據定義的單個靜態集合 用作新創建的類型實例的工作 默認值。相反,您必須確保您有意將收集值設置爲唯一(實例)集合作爲類構造函數邏輯的一部分。 否則,您將創建一個無意的單例類。

指定默認值爲new List<LeafControlItem>(),使所有LeafControl的實例共享列表的同一個實例。因此,在該列表中添加和刪除對象將反映在所有LeafControl實例中。所以,實際上你已經爲LeafControl的所有實例創建了singleton列表。

首先,你應該避免指定的默認值的新名單 -

public static readonly DependencyProperty ItemsProperty = 
      DependencyProperty.Register(
       "Items", typeof(List<LeafControlItem>), typeof(LeafControl)); 

第二,你應該把它在你的列表控件類的構造函數設置它讓每一個實例都有初始化新的列表中的自己份額的名單 -

public LeafControl() 
{ 
    SetValue(ItemsPropertyKey, new List<LeafControlItem>()); 
} 
相關問題