首页 > 解决方案 > 可观察的堆栈面板

问题描述

我需要将 ListBoxes 的 ObserveableCollection 作为我的列,并将按钮的 ObserveableCollection 作为我的 ListBox 任务。

问题是我创建了一个水平 StackPanel。

<StackPanel Name="panel" Orientation="Horizontal">
</StackPanel>
    public partial class MainWindow : Window
    {
        private ListBox currentList;
        public MainWindow()
        {
            InitializeComponent();

        }

        private void Button_Click2(object sender, RoutedEventArgs e)
        {
            currentList = new ListBox();
            Button b1 = new Button();
            b1.Content = "Add Card";
            b1.Height = 23;
            b1.Width = 100;
            b1.Click += B1_Click;
            currentList.Items.Add(b1);
            panel.Children.Add(currentList);
        }

        private void B1_Click(object sender, RoutedEventArgs e)
        {
            Button currentButton = (Button)sender;
            currentList = ((ListBox)currentButton.Parent);
            Button bt = new Button();
            bt.Content = "task";
            bt.Height = 23;
            bt.Width = 100;
            currentList.Items.Add(bt);
        }
    }

所以这是我得到的结果:

https://imgur.com/nmvzfpI

这正是我需要的,只是我需要绑定 StackPanel结果是:

https://imgur.com/dO5WfOS

标签: c#wpf

解决方案


这是一个示例,说明如何更好地实现您想要做的事情,但使用ItemsControlin Xaml。这通过绑定到集合中并在集合中ObservableCollection创建一个ListBoxforeach 项目来工作。然后将ListBox其绑定到ObservableCollection内部以显示每个单独的项目。

<ItemsControl ItemsSource="{Binding MyCollection}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <ListBox ItemsSource="{Binding}" Width="100" Height="auto">

            </ListBox>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

private ObservableCollection<ObservableCollection<string>> _myCollection;

public ObservableCollection<ObservableCollection<string>> MyCollection
{
    get { return _myCollection; }
    set { _myCollection = value; NotifyPropertyChanged }
}

推荐阅读