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

4
我在窗口上有一个TreeView控件,根据用户选择的不同,应该显示一个用户控件(确定要显示哪个用户控件已经完成)。我现在遇到的问题是如何实际显示用户控件。基本上,用户会从TreeView中选择项目,根据选择,用户控件将出现(我假设是在ContentControl控件中)。
目前,为了打开新窗口,我有一个窗口适配器,可以动态创建新窗口并设置父级。
如何在我的视图模型中实现这一点?
编辑
这就是我认为Rachel提到使用DataTemplate时所说的内容。不要担心我的DataTemplates,而是DataType属性。那只是我的项目名称。
<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>

这里是一个示例视图模型。

public class ViewModel
{
    public IEditorViewModel Editor
    {
        get
        {
            return new BarEditorViewModel();
        }
    }
}

使用以下方法将它们粘合在一起

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

我不得不创建一个名为IEditorViewModel的空接口,以便返回不同的用户控件编辑器。不确定是否有其他方法可以绕过这个问题。
希望这能帮助到某些人。
1个回答

5

你选择的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>

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接