UUser
UUser

Reputation: 59

is there a way to close Usercontrol from ViewModel in WPF

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 :

Close View from ViewModel

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

Upvotes: 0

Views: 1813

Answers (1)

Yury Schkatula
Yury Schkatula

Reputation: 5369

The answer is: you should not close your usercontrols (unless they're used as separate dialogs, and this is not your case, according to your comment above).

All changes in usercontrols visibility are about navigation. Once you logically navigate to a functionality involving another usercontrol, you have to hide old one and show new control. Usually this is done via template selection:

Two templates, one per UserControl, each associated with respective ViewModel:

<DataTemplate DataType="{x:Type ViewModels:FirstViewModel}">
    <controls:FirstControl />
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModel:SecondViewModel}">
    <controls:SecondControl />
</DataTemplate>

Then later we declare a placeholder:

<ContentControl Content="{Binding ViewModelSelector}" />

Once ViewModelSelector property returns FirstViewModel, our placeholder will show FirstControl. If we navigate ViewModelSelector property to SecondViewModel, our placeholder would auto-replace FirstControl with SecondControl and vice versa.

Upvotes: 1

Related Questions