Search code examples
c#wpfmvvmcaliburn.microdynamic-usercontrols

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?


Solution

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