2013-02-17 59 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

相关问题