-1

我创造了UserControl这样的:

MyUserCtrl myctrl = new MyUserCtrl() { DataContext = new MyViewModel()};
ControlCollection.Add(myctrl);

我用它把它输出ItemsControl ItemsSource="{Binding ControlCollection}"到视图。

它干净漂亮,但问题是我不知道如何关闭UserControls我打开的那些。

如果我只是将它删除到集合中怎么办。因此视图模型也会关闭吗?

4

1 回答 1

3

不要将 UI 元素的集合分配给 ItemsControl 的 ItemsSource。相反,将 UI 元素放在 ItemsControl 中ItemTemplate,并将视图模型实例的集合传递给 ItemsSource。

<ItemsControl ItemsSource="{Binding MyItems}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <local:MyUserCtrl />
        </DataTemplate>
    </ItemsCControl.ItemTemplate>
</ItemsCControl>

将视图模型项添加到“主”视图模型中的集合属性:

var item = new MyViewModel();
MyItems.Add(item);

要“关闭”控件,请从集合中删除相应的项目:

MyItems.Remove(item);
于 2018-11-12T18:48:25.447 回答