I have one Window with multiple Frames. Each Frame holds one or more Pages. All Pages use the same ViewModel. I control the Visibility of each Frame to manipulate the UI.
I've recently realized that when my program launches each of the Pages are firing the same Constructor of the ViewModel (so the same constructor is firing multiple times) (a simple MessageBox.Show in the constructor fires multiple times at launch). It kind of makes sense to me why this is happening, but not what I want.
Also, I've come to believe that the reason I am having trouble manipulating the different frames in C# is because I may have created new "objects" of the ViewModel?? I'm not exactly sure if this is what's happening, but I'm pretty sure it is not what I want.
Is there a way of setting the DataContext (in Xaml) for the Pages so that the Constructor fires only once, but also still sets each pages' DataContext to the ViewModel? Or is there a different approach I should be exploring? I am still learning...
Each Page has the following Xaml:
<Page.DataContext>
<ViewModel:ActiveJobViewModel/>
</Page.DataContext>
my Frames look like this. I realize a single frame can hold multiple pages, but manipulating the visibility gave me better performance and I don't want the Constructor to run every time the Page source changes.
<Frame Source="ActiveJobPage.xaml" Grid.Row="2" Grid.Column="3"
Visibility="{Binding ElementName=ActiveJobPageToggleButton, Path=IsChecked, Converter={StaticResource booleanToVisibility}, UpdateSourceTrigger=PropertyChanged}"
Style="{StaticResource FramePage}">
</Frame>
<Frame Source="CustomerPage.xaml" Grid.Row="2" Grid.Column="3"
Visibility="{Binding objHomePage_PageVisibility.CustomersPageToggleButtonIsChecked, Converter={StaticResource booleanToVisibility}, UpdateSourceTrigger=PropertyChanged}"
Style="{StaticResource FramePage}">
</Frame>
Remove the following from Page XAML.
<Page.DataContext>
<ViewModel:ActiveJobViewModel/>
</Page.DataContext>
And set the DataContext of both pages to the same instance in the code manually.
For example in your Page codebehind class.
public void SetDataContext(ActiveJobViewModel commonContext)
{
this.DataContext = commonContext;
}
Then create a common instance of ActiveJobViewModel instance and set the same datacontext for multiple pages.