We are using Silverlight MVVM pattern in our application. In the application there is a mainpage (which does not change) and there are child pages, these child pages changes depending on the operation performed by the user. Untill now I have been using code-behind for navigation between different child pages, the code goes like this :
ChildPage2 开发者_开发问答obj = new ChildPage2 ();
Dialog_Box.Children.Clear();
Dialog_Box.Visibility = Visibility.Visible;
Dialog_Box.Children.Add(obj );
But as I am using MVVM pattern I want to do the same using my ViewModel. Is there a way to do the same (Navigation) using ViewModels.
Please help, thanks in advance.
Vaibhav
Couple of basic rules:
- ViewModels should not know about how they are displayed. They are purely glue between views and real data objects & business logic.
- Views only know how to display data with a certain shape. They should not know where the data is coming from (the exception that breaks this rule is using DomainDataSources... but that's another story).
Look at the navigation features available in Silverlight (try creating a sample Business application in Visual Studio). Your views are then created when hyperlinks are clicked based on configured mappings.
The alternative (to do it in code) is to introduce controllers into MVVM. This maintains the separation of concerns between views, viewmodels and data, but adds a level of complexity I usually reserve for PRISM-based apps. Best you try the hyperlink/url mapping option.
The way I solved this before was to have properties in the ViewModel that each child page would bind to:
public class YourViewModel : INotifyPropertyChanged
{
public Visibility FooVisibility { get { /* ... */ } }
public Visibility BarVisibility { get { /* ... */ } }
}
精彩评论