C# 如何根据用户选择动态注入用户控件

C# 如何根据用户选择动态注入用户控件,c#,wpf,mvvm,user-controls,C#,Wpf,Mvvm,User Controls,我的窗口上有一个TreeView控件,它根据用户选择的选项显示用户控件(确定要显示的用户控件是完整的)。我在弄清楚如何实际显示用户控件时遇到了问题。本质上,用户将从TreeView中选择项,并根据选择显示一个用户控件(在我假设的ContentControl控件中) 目前,为了打开新窗口,我有一个窗口适配器,可以在其中动态创建新窗口并设置父窗口 如何在视图模型中实现这一点 编辑 以下是我相信Rachel在提到使用DataTemplate时所说的内容。不要担心我的数据模板,而是数据类型属性。这只是我

我的窗口上有一个
TreeView
控件,它根据用户选择的选项显示用户控件(确定要显示的用户控件是完整的)。我在弄清楚如何实际显示用户控件时遇到了问题。本质上,用户将从
TreeView
中选择项,并根据选择显示一个用户控件(在我假设的
ContentControl
控件中)

目前,为了打开新窗口,我有一个窗口适配器,可以在其中动态创建新窗口并设置父窗口

如何在视图模型中实现这一点

编辑 以下是我相信Rachel在提到使用
DataTemplate
时所说的内容。不要担心我的
数据模板
,而是
数据类型
属性。这只是我项目的名称

<Window.Resources>
    <DataTemplate DataType="{x:Type DataTemplates:FooEditorViewModel}">
        <DataTemplates:FooControl></DataTemplates:FooControl>
    </DataTemplate>
    <DataTemplate DataType="{x:Type DataTemplates:BarEditorViewModel}">
        <DataTemplates:BarControl></DataTemplates:BarControl>
    </DataTemplate>
</Window.Resources>
用胶水把它粘在一起

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

为了返回不同的用户控件编辑器,我必须创建一个名为
IEditorViewModel
的空白界面。不知道有没有办法


希望这对其他人有所帮助。

您选择的TreeViewItem将存储在您的ViewModel中,该值将用于确定要显示的项目

例如:

<ContentControl Content="{Binding SelectedItem}">
    <ContentControl.Style>
        <Style TargetType="{x:Type ContentControl}">
            <Setter Property="ContentTemplate" Value="{StaticResource DefaultTemplate}" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding SelectedItem}" Value="{x:Type local:ItemA}">
                    <Setter Property="ContentTemplate" Value="{StaticResource TemplateA}" />
                </DataTrigger>
                <DataTrigger Binding="{Binding SelectedItem}" Value="{x:Type local:ItemB}">
                    <Setter Property="ContentTemplate" Value="{StaticResource TemplateB}" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ContentControl.Style>
</ContentControl>

更好的替代方法是为不同的项目使用数据模板。然后您只需设置
Content=“{Binding SelectedItem}”
,WPF将解析要使用的正确数据模板。我只是首先展示了上面的示例,因为它可以用来根据SelectedItem的属性创建模板

<ContentControl Content="{Binding SelectedItem}">
    <ContentControl.Style>
        <Style TargetType="{x:Type ContentControl}">
            <Setter Property="ContentTemplate" Value="{StaticResource DefaultTemplate}" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding SelectedItem}" Value="{x:Type local:ItemA}">
                    <Setter Property="ContentTemplate" Value="{StaticResource TemplateA}" />
                </DataTrigger>
                <DataTrigger Binding="{Binding SelectedItem}" Value="{x:Type local:ItemB}">
                    <Setter Property="ContentTemplate" Value="{StaticResource TemplateB}" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ContentControl.Style>
</ContentControl>