简体   繁体   中英

How to close User Control from its View Model

I created my UserControl like this:

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

and i output it using this ItemsControl ItemsSource="{Binding ControlCollection}" to the View.

It's clean and nice but the problem is I don't know how can I close those UserControls that I opened.

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. Instead, put the UI element in the ItemsControl's ItemTemplate and pass a collection of view model instances to the 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:

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

To "close" a control, remove the appropriate item from the collection:

MyItems.Remove(item);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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