WPF MVVM: How to load views “on demand” without using plug-in architecture?

后端 未结 1 1727
醉话见心
醉话见心 2021-01-06 07:08

I have an Outlook-like WPF UI with navigation on the left, a toolbar on top, and a status bar at the bottom, all within a DockPanel.

The "main"

相关标签:
1条回答
  • 2021-01-06 07:43

    Here's what I do:

    First, on your main ViewModel (the one that's servicing the main window), add a Content property:

    object _content;
    public object Content
    {
        get { return _content; }
        set
        {
            _content = value;
            RaisePropertyChanged("Content");
        }
    }
    

    When the user switches from view to view, set the Content property to the appropriate ViewModel for that view they've selected.

    In the main window, then, you can display the current Content ViewModel using a ContentControl:

    <ContentControl Content="{Binding Content}" />
    

    ... and somewhere above that, define a DataTemplate for each of the various ViewModels that Content might be set to:

    <DataTemplate DataType="{x:Type vm:FooViewModel}">
        <my:FooUserControl />
    </DataTemplate>
    
    <DataTemplate DataType="{x:Type vm:BarViewModel}">
        <my:BarUserControl />
    </DataTemplate>
    

    So now the ContentControl will be responsible for initializing and displaying each of your UserControls depending on which ViewModel is currently "active".

    0 讨论(0)
提交回复
热议问题