2011-03-01 51 views
2

我想在我的Silverlight MVVM應用程序中創建一個「嚮導」。該向導應包含多個步驟,您可以使用「next」和「previous」進行導航。 我面臨的問題是視圖和視圖模型之間的關係。 我希望有一個視圖和視圖模型的嚮導本身。我的直覺告訴我,嚮導中的每一步都應該有一個視圖/視圖模型對。如何使用Silverlight和MVVM設計複合視圖和視圖模型?

維護這些關係的好方法是什麼?一個視圖模型包含多個其他視圖模型,而視圖實際上包含幾個較小的視圖? 我可以使用任何模式或做法嗎?

我知道這個問題可能是主觀的,但給我一個粗略的方法,我會給你一個答案!

回答

4

我建議主嚮導viewModel有一個steps視圖模型的集合並處理它們之間的導航。在瀏覽它應該調用的驗證方法中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

視圖可以用的ViewModels經由Datatemplating耦合。例如添加到這個資源App.Xaml

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

你的ViewModels應該知道絕對沒有關於意見。這意味着WizardVM應該 只公開其他viewModels但不公開視圖。這是MVVM的經驗法則。

UPDATE2糟糕,我忘了Silverlight還沒有DataTemplating。在Silverlight中,我仍然會公開ViewModels,但使用轉換器將它們綁定到ContentPresenters,轉換器會將viewModel轉換爲相應的視圖。

+0

哇,這很快! 但是......我很好奇,你認爲CurrentStep屬性應該是可見的東西(I.E一個視圖)?否則,我不會看到ContentPresenter如何呈現它。我的問題是將包含的視圖和視圖模型與海誓山盟聯繫起來。 – 2011-03-01 22:08:43

+0

@Per,'CurrentStep'應該公開Step ViewModel。查看更新後的答案 – Snowbear 2011-03-01 22:14:23

+0

好的...使用值轉換器將視圖模型轉換爲視圖。這是相當操縱,ehrm ..我的意思是務實的:)但不過,我沒有想到一個新的方法!我懷疑這是我將要去做的事情,但是我將授予你創新的答案,甚至超出我自己的(而非操縱性的)本質......感謝您花時間回覆! – 2011-03-02 06:20:02