I am working on a WPF application which is developed using MVVM pattern. The MainWindow has several Usercontrols that open when an action is performed. However, I want to close the Usercontrol once the actions are complete and on Clicking a button. I have looked in several places, but haven't had any luck with it so far. Any help would be appreciated.
It is being pointed out that my question is a duplicate of this :
But it is actually not, since that thread talks about closing a Window, mine is about closing an UserControl.
Adding some code to make it clear:
This is the ItemsControl in the first UserControl which hosts the second Usercontrol:
<Grid x:Name="UserControlGrid" Width="Auto" Height="auto" Margin="0,0,0,0">
<ItemsControl ItemsSource="{Binding ViewsToShow}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid IsItemsHost="True" Width="auto" Height="auto"></Grid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Grid>
Now to open the second UserControl , in the first UserControl ViewModel, I do this:
private ObservableCollection<ObservableObject> viewsToShow = new ObservableCollection<ObservableObject>();
public ObservableCollection<ObservableObject> ViewsToShow
{
get
{
return viewsToShow;
}
set
{
viewsToShow = value;
OnPropertyChanged("ViewsToShow");
}
}
ViewsToShow.Add(new SecondUserControlViewModel());
Thank you
UserControl
in WPF cannot be "closed" because it cannot be "opened". AUserControl
always requires a host where it can be displayed (aWindow
, aPage
, aContentControl
, etc). What do you mean by "close aUserControl
"? – dymanoidItemsSource="{Binding ViewsToShow}"
and usingAdd
from your ViewModel, you should also be able to useRemove
– Martin Backasch