How do i design a composite view and view model using Silverlight and MVVM?

折月煮酒 提交于 2019-12-06 13:31:24

I'd propose main wizard viewModel which has a collection of steps view models and handles navigation between them. While navigating it should call validation methods in step viewModels:

WizardVM:

public class WizardVM
{
     // this commands should support CanExecute
     public ICommand GotoNextCommand { get; private set; } // should open next step VM
     public ICommand GotoBackCommand { get; private set; } // should open previous step VM

     // this prop should be set by 'GotoNext', 'GotoBack' commands
     public object CurrentStep { get; private set; }

     // probably internally you will have a list of all steps:
     private ICollection<object> _stepViewModels = ...;
}

WizardView:

<StackPanel>
    <ContentPresenter Content="{Binding CurrentStep}">
    <StackPanel Orientation="Horizontal">
        <Button Command="{Binding GotoBackCommand}">Back</Button>
        <Button Command="{Binding GotoNextCommand}">Next</Button>
    </StackPanel>
</StackPanel>

UPDATE:

Views can be coupled with ViewModels via Datatemplating. For example add this into resources in App.Xaml:

<DataTemplate DataType="{x:Type local:Step1ViewModel}">
     <Step1View />
</DateTemplate>
<DataTemplate DataType="{x:Type local:Step2ViewModel}">
     <Step2View />
</DateTemplate>

Your viewModels should know absolutely nothing about views. It means that WizardVM should expose only other viewModels but not views. It's a rule of thumb for MVVM.

UPDATE2 Oops, I forgot that Silverlight doesn't have DataTemplating yet. In silverlight I would still expose ViewModels but bind them to ContentPresenters using a converter which will convert a viewModel into corresponding view.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!