VansFannel VansFannel - 3 months ago 17
C# Question

Access a ViewModel from another ViewModel

I'm developing an WPF using MVVM pattern, C# and .NET Framework 4.6.1.

I have a Window that contains an UserControl (

Control1
) and that UserControl contains another UserControl (
Control2
). I have chosen this way to do it instead of using a Dialog Window (
Control2
acts as Dialog Window).

Both user controls have a Viewmodel (
Control1VM
and
Control2VM
).

I use
Control2
as a form to let users input some data that I need to start the application.

This is the MainWindow with
Control1
:

enter image description here

And this is
Control2
over
Control1
.

enter image description here

My problem is that I don't know how to hide
Control2
when I click on OK or Cancel button.

This is how
Control2
is set on
Control1
:

<Grid x:Name="gridControl2" Margin="30" Grid.RowSpan="6" Grid.ColumnSpan="3" Visibility="{Binding GridControl2Visibility}">
<local:Control2 x:Name="userControlControl2" />
</Grid>


To show
Control2
and set
GridControl2Visibility
to
Visible
in
Control1VM
:

public Visibility GridControl2Visibility
{
get { return gridControl2Visibility; }
set
{
if (gridControl2Visibility != value)
{
gridControl2Visibility = value;

RaisePropertyChangedEvent("GridControl2Visibility");
}
}
}


How can I hide
Control2
when I click on Ok or Cancel button in
Control2
? My problem is that
GridControl2Visibility
is on
Control1VM
and I can't access that class from
Control2VM
.

Answer

Use a service that both view models can access and that stores the info whether Control2 should be visible or not. Ideally, the service would be registered as singleton with your di-container and injected into the view models.

Alternatively, you can use an event aggregator, which is basically a singleton service, too, but focused on distributing events rather than holding a state.