WPF: switching UserControls depending on corresponding ViewModels (MVVM)

前端 未结 2 1720
终归单人心
终归单人心 2021-02-01 06:22

I\'ll try to simplify the task I\'m working on by imagining this example:

Let\'s suppose that we have the following hierarchy of model classes:

Animal
           


        
相关标签:
2条回答
  • 2021-02-01 06:31

    Is it possible to deduce the necessary user control based on a ViewModel type?

    You mean, like this?

    <Window.Resources>
       <DataTemplate DataType="{x:Type vm:LionViewModel}">
          <v:LionView />
       </DataTemplate>
       <DataTemplate DataType="{x:Type vm:SnakeViewModel}">
          <v:SnakeView />
       </DataTemplate>
       <DataTemplate DataType="{x:Type vm:BirdViewModel}">
          <v:BirdView"/>
       </DataTemplate>
    </Window.Resources>
    

    See "Applying a View to a View Model" in Josh Smith's article on MVVM.

    Edit:

    Here's a trivial example of type-based template selection that you can paste into Kaxaml to prove to yourself that it really works:

    <Page
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:sys="clr-namespace:System;assembly=mscorlib">
      <Page.Resources>
        <sys:String x:Key="string">this is a string</sys:String>
        <sys:Int32 x:Key="int32">1234</sys:Int32>
        <DataTemplate DataType="{x:Type sys:String}">
          <TextBlock Foreground="Red" Text="{Binding}"/>
        </DataTemplate>
        <DataTemplate DataType="{x:Type sys:Int32}">
          <TextBlock Foreground="Blue" Text="{Binding}"/>
        </DataTemplate>
      </Page.Resources>
      <StackPanel>  
        <ContentControl Content="{Binding Source={StaticResource string}}"/>
        <ContentControl Content="{Binding Source={StaticResource int32}}"/>
      </StackPanel>
    </Page>
    
    0 讨论(0)
  • 2021-02-01 06:51

    You can use DataTemplateSelector for that. The method of choosing the right template is up to you. You can use enums or test for class type if you wish.

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