I've seen this done inside of an event handler directly behind the .xaml file however it doesn't seem like this would follow the MVVM pattern: MainApplication.mainFrame.Navigate(new HomePage());
. Is there a better way for handling navigation with the MVVM pattern perhaps in the ViewModel? or in the XAML?
views:
188answers:
2If you are looking for showing different UserControls based on the context of your data, then just understand the following simple DataBinding and DataTemplate concept and expand on it. Imagine you got a Property called CurrentViewModel which binds to the Content of a ContentControl inside your Window
<Window ...
<ContentControl Content="{Binding CurrentViewModel}" />
</Window>
Now imagine that you got ViewModel classes ClassA and ClassB, so appropriately set the instances to CurrentViewModel and define global DataTemplates (Views) for your classes
<DataTemplate DataType="{x:Type vm:ClassA}">
<local:UserControlForA../>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:ClassB}">
<local:UserControlForB../>
</DataTemplate>
Now the View is automatically controlled from ViewModel logic and WPF will take care of showing the UserControl by Datatemplate.
If you are not familiar with MVVM better use this article. http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
I think what you're trying to do would be more simply done if you had the navigation in another class. See below
public class FirstViewModel
{
}
public class SecondViewModel
{
}
public class NavigateViewModel
{
public ViewModelBase CurrentVieModel {get;set;}
public bool CanNavigate
{
get { return true;//Or Add some custom logic here determine if you can navigate}
}
public void Navigate()
{
//Just some arbitrary code
if(CurrentViewModel is FirstViewModel)
CurrentViewModel = new SecondViewModel();
}
}
Now just 1) bind the Page Content to CurrentViewModel 2) Wrap the Navigate Method in an ICommand and you're set
Might not meet your needs, hope it helps