Reputation: 223
Im having problem sharing a windows viewmodel to the windows hosted frame.
Therefore I made a static viewmodel for the mainwindow, so any class can edit it´s properties:
class GUICollection
{
public static MainWindowViewModel MainWindowViewModel = new MainWindowViewModel();
}
This is then set into the MainWindows datacontext:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = GUICollection.MainWindowViewModel;
}
}
This is the windows xaml:
<Window x:Class="MVVMFrameQuestiontoStackOverflow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Frame NavigationUIVisibility="Hidden" Source="{Binding MainWindow.FrameURI}"/>
</Grid>
It´s view model:
class MainWindowViewModel
{
private string startUpURI;
private object startUpDataContext;
private MainWindowModel mainWindow;
public MainWindowViewModel()
{
startUpURI = "pack://application:,,,/MVVMFrameQuestiontoStackOverflow;component/Page1.xaml";
mainWindow = new MainWindowModel(startUpURI);
}
/// <summary>
/// Gets the MainWindow instance
/// </summary>
public MainWindowModel MainWindow
{
get
{
return mainWindow;
}
}
}
So from here I can choose the frame Source, which means I can choose which view to show. However Im wondering if I could avoid the static initiliazing and still being able to access the mainwindows FrameURI property (Here is my current logic):
public Page1()
{
InitializeComponent();
DataContext = new MainMenuViewModel();
//Statement below causes an exception, but the whole issue is about accesing this without using a static instance.
GUICollection.MainWindowViewModel.MainWindow.FrameURI = "Change MainWindows FrameURI property!";
}
Is the same behaviour able to produce without using a static class? If so an example would be warmly appreciated.
Thanks on advance!
Upvotes: 0
Views: 222
Reputation: 81
I think in fact you problem is that you haven't understood MVVM and use a mix between MVC and MVVM : You create the view (mainWindows) in the ViewModel wich is forbidden.
Your App must load the main view.
In the constructor of the main view you should create the view-model as a private field.
When you will create new windows (and you should only do that from view, never from viewmodel) you will give the viewmodel datacontext object as a parameter for the new view, wich will give it to it's own viewmodel via parameters.
If you have Model object(s) wich is(are) shared throught all the application, create it in the App launch method, and pass it throught views via their constructors as a parameter.
Upvotes: 1