Navigation in MVVM
Navigation in MVVM
One of the main issues regarding Silverlight was the navigation issue,
what commonly refers as “How can we support browser’s back button”.
Although Microsoft has standard solution for that is somewhat limited. It’s
limitation concerns two main issues:
1. Navigation requires as to use Page Navigation and not user controls
2. It won’t support scenario when pressing a link changes the internal state
but will replace the entire page instead.
In this post, I’ll demonstrate how we can overcome these issues.
The post content is based on material leaned from Elad Katz of which
I’m trying to implement everywhere I can.
What do we need exactly to overcome the two limitation written above:
We need to have a class that acts as Navigation Service. The service should contain
an underlying Navigation Frame and handle all it’s events. One close look on the
automatically made Silverlight Navigation application reveals that the MainPage
does it exactly.
Because this service will serve our entire application it is SingleTon, we initally
send our navigation frame as parameter to the InitializeFrame method which look
like that:
public void InitializeFrame(Frame frame)
{
_frame = frame;
_frame.Navigated += (sender, e) =>
{
if (Navigated != null)
Navigated(this, e);
};
_frame.Navigating += (sender, e) =>
{
if (Navigating != null)
Navigating(this, e);
};
_frame.NavigationFailed += (sender, e) =>
{
if (NavigationFailed != null)
NavigationFailed(this, e);
};
_frame.NavigationStopped += (sender, e) =>
{
if (NavigationStopped != null)
NavigationStopped(this, e);
};
}
The service holds the same events as the navigation frame and invokes them, ,moreover it sets a private member with typed Frame called _frame which. This private member is the
same frame defined in the main page, where it’s entire code-behind looks exactly like that:
public partial class NavigationFrame : UserControl
{
public NavigationFrame()
{
InitializeComponent();
NavigationService.Instance.InitializeFrame(MyFrame);
}
}
The navigation frame is the main page of our application – the same
as the navigation application template in visual studio.
Now, every ViewModel can interact with the NavigationService, it can subscribe
to it’s events and from this point further, the sky is the limit…
In Conclusion:
In this post I discussed the limitation of Silverlight Navigation and introduced the
Navigation service. Doing it right can make our application support the “Back / Forward”
buttons of our browser.
I’ve chosen to demonstrate it through a simple RSS reader. You can download code example
here. The application’s UI may not look so good, but hey – It’s MVVM. you can change it easily…