简体   繁体   English

如何从其视图模型关闭用户控件

[英]How to close User Control from its View Model

I created my UserControl like this: 我这样创建了UserControl

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

and i output it using this ItemsControl ItemsSource="{Binding ControlCollection}" to the View. 我使用此ItemsControl ItemsSource="{Binding ControlCollection}"将其输出到视图。

It's clean and nice but the problem is I don't know how can I close those UserControls that I opened. 干净而且不错,但是问题是我不知道如何关闭那些打开的UserControls

And what if I just remove it to the collection. 如果我只是将其删除到集合中,该怎么办。 Thus the View Model will close too? 因此,视图模型也将关闭吗?

Do not assign a collection of UI elements to the ItemsSource of an ItemsControl. 不要将UI元素的集合分配给ItemsControl的ItemsSource。 Instead, put the UI element in the ItemsControl's ItemTemplate and pass a collection of view model instances to the ItemsSource. 而是将UI元素放在ItemsControl的ItemTemplate然后将视图模型实例的集合传递给ItemsSource。

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

Add a view model item to the collection property in your "main" view model: 将视图模型项添加到“主”视图模型中的collection属性中:

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

To "close" a control, remove the appropriate item from the collection: 要“关闭”控件,请从集合中删除相应的项:

MyItems.Remove(item);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM