简体   繁体   中英

C# WPF MVVM XAML: Using ContentPresenter Style to display ViewModel

So I have a series of pages that I want to display for an application I am working on but I want to start by simply displaying a ViewModel with a ContentPresenter within another ViewModel. I can make it work if I use:

<ContentPresenter>
 <ContentPresenter.Content>
  <connection:ConnectionSelectPage />
 </ContentPresenter.Content>
</ContentPresenter>

I want to make it more advanced using Styles because I will need to be able to switch which Viewmodel is displayed based on a DataTrigger. I have come up with this as a start before delving into the DataTriggers and multiple ViewModels which I want to simply perform the exact same function as the above code:

<ContentPresenter>
 <ContentPresenter.Resources>
  <Style x:Key="ConnectPage">
    <Setter Property="ContentPresenter.Content">
      <Setter.Value>
        <connection:ConnectionSelectPage />
      </Setter.Value>
    </Setter>
  </Style>
 </ContentPresenter.Resources>
</ContentPresenter>

This new code does not display anything in the application and I find that confusing because from what I thought I knew about XAML and WPF, these two blocks of code should be identical. Am I missing something?

Just set your content presenters Content binding to the page property in your main view model...

<ContentPresenter Content='{Binding CurrentPage}' />

...where CurrentPage is of type 'object' or, better yet, some base class you're using for all your page view models. Then you just use data templates to dictate how the ContentPresenter should be populated for each of your page types:

<DataTemplate DataType="{x:Type Page1ViewModel}">
    <views:Page1UserControl />
</DataTemplate>

<DataTemplate DataType="{x:Type Page2ViewModel}">
    <views:Page2UserControl />
</DataTemplate>

... etc ...

So long as the CurrentPage property supports property change notification the child views will automatically change whenever you change its value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM