如何在自定义StackPanel中为特定的自定义控件创建项目列表



我想创建一个从StackPanel派生的自定义StackPanel。但是为了添加项目,我想创建一个特殊的列表(可以使用list<>或ObservableCollection<>.)。应该是这样的,

<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,如果我添加项目,它会非常有效。intellisense也只显示了一个可以添加的MyControl。

现在,如何从集合中获取列表并将其添加到StackPanel,即使用stkPanel。儿童Add()。

我应该使用Panel吗?或者如何获取列表并添加到Panel?提前谢谢。

PS:我尝试了几个选项,但列表总是空的,包括使用ItemsControl。所以我可能遗漏了一些要点。再次使用ItemsControl不适合我的场景,因为我只想要一个可以添加到面板中的控件类型。

使用ObservableCollection的collection changed事件来保持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>

最新更新