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

Mik*_*ike 4 c# wpf user-controls mvvm

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

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

如何在我的视图模型中完成此操作?

编辑

以下是我相信雷切尔在提到使用时所说DataTemplate的话.不要担心我DataTemplatesDataType属性.这只是我项目的名称.

<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>
Run Code Online (Sandbox Code Playgroud)

这是一个示例视图模型.

public class ViewModel
{
    public IEditorViewModel Editor
    {
        get
        {
            return new BarEditorViewModel();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并将它们粘在一起

<ContentControl Content="{Binding Editor}" />
Run Code Online (Sandbox Code Playgroud)

我必须创建一个空白接口IEditorViewModel,以便返回不同的用户控件编辑器.不确定是否有任何解决方法.

希望这有助于某人.

Rac*_*hel 5

您的SelectedTreeViewItem将存储在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>
Run Code Online (Sandbox Code Playgroud)

更好的选择是将DataTemplates用于不同的项目.然后你只需设置你的Content="{Binding SelectedItem}"WPF将解析正确的DataTemplate使用.我首先展示了上面的例子,因为它可以用来将你的模板基于SelectedItem的属性