2013-02-17 25 views
0

我想創建一個從StackPanel派生的自定義StackPanel。但要添加項目,我想創建一個特殊列表(可以使用列表<>或ObservableCollection <>)。它應該是這樣的,如何在自定義的StackPanel中爲特定的自定義控件創建項目列表?

<mc:MyStackPanel> 
    <mc:MyStackPanel.Items> 
    <mc:MyControl Content="A" /> 
    <mc:MyControl Content="B" /> 
    <mc:MyControl Content="C" /> 
    </mc:MyStackPanel.Items> 
</mc:MyStackPanel> 

不喜歡這個(目前這一工作),

<mc:MyStackPanel> 
    <mc:MyControl Content="A" /> 
    <mc:MyControl Content="B" /> 
    <mc:MyControl Content="C" /> 
</mc:MyStackPanel> 

我嘗試使用的ObservableCollection和它完美的作品,如果我添加的項目。智能感知還顯示只能添加一個MyControl。

現在,如何從集合中獲取列表並將其添加到StackPanel,即使用stkPanel.Children.Add()。

我應該用面板代替,還是如何得到列表並添加到面板?提前致謝。 PS:我嘗試了幾個選項,但列表總是空的,包括使用ItemsControl。所以我可能在這裏錯過了一些觀點。再次使用ItemsControl不適合我的場景,因爲我只想要一個可以添加到面板的控件類型。

+0

你需要索引,選擇支持? – 2013-02-17 05:37:49

+0

我認爲索引是列表中的一部分。我只想知道機械師在XAML中獲取列表,以便將它添加到StackPanel子項目中。 – Rizzo 2013-02-17 07:30:50

回答

0

如何使用ObservableCollection的集合更改事件來保持Children屬性的同步?我還包含ContentProperty屬性,因此您不必將項目顯式添加到XAML中的集合中,如果需要,可以將其刪除。

[ContentProperty("CustomItems")] 
public class MyCustomStackPanel : StackPanel 
{ 
    public MyCustomStackPanel() 
    { 
     CustomItems = new ObservableCollection<MyUserControl>(); 
    } 

    private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) 
    { 
     if (e.NewItems != null) 
     { 
      foreach (object element in e.NewItems) 
      { 
       Children.Add((UIElement) element); 
      } 
     } 

     if (e.OldItems != null) 
     { 
      foreach (object element in e.OldItems) 
      { 
       Children.Remove((UIElement)element); 
      } 
     } 
    } 

    private ObservableCollection<MyUserControl> _customItems; 
    public ObservableCollection<MyUserControl> CustomItems 
    { 
     get { return _customItems; } 
     set 
     { 
      if(_customItems == value) 
       return; 

      if (_customItems != null) 
       _customItems.CollectionChanged -= OnCollectionChanged; 

      _customItems = value; 

      if (_customItems != null) 
       _customItems.CollectionChanged += OnCollectionChanged; 
     } 
    } 
} 

的XAML則看起來像這樣(與當地的命名空間指向該項目的自定義控件中)

<local:MyCustomStackPanel> 
    <local:MyUserControl></local:MyUserControl> 
</local:MyCustomStackPanel> 
+0

@Darklce:是的,它的工作。謝謝。我可以添加的項目現在這個樣子, <地方:MyCustomStackPanel> <地方:MyCustomStackPanel.CustomItems> <地方:的MyUserControl /> 但對於添加和刪除事件OnCollectionChanged是常見的/最佳做法? – Rizzo 2013-02-18 01:12:12

+0

@Rizzo你的意思是添加/刪除setter中的事件?如果是這樣,那麼你需要確保沒有對事件處理程序的引用,否則垃圾回收器將無法收集該對象,並且會產生內存泄漏。實際上,如果引用已更改(如果_customItems == value),則返回;)。 – ChrisWay 2013-02-18 08:02:39

+0

好的。我知道了。非常感謝。 – Rizzo 2013-02-18 12:23:05

相關問題