How to close User Control from its View Model

108 views Asked by At

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?

1

There are 1 answers

0
Clemens On BEST ANSWER

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);