【问题标题】:How to dynamically inject a user control based on user selection如何根据用户选择动态注入用户控件
【发布时间】:2011-05-27 18:13:56
【问题描述】:

我的窗口上有一个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 的空白界面,以便返回不同的用户控件编辑器。不知道有没有办法解决。

希望这对某人有所帮助。

【问题讨论】:

    标签: c# wpf mvvm user-controls


    【解决方案1】:

    您的 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>
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-21
      • 2023-04-09
      • 2022-06-30
      • 2020-05-24
      • 2022-07-08
      • 1970-01-01
      • 1970-01-01
      • 2016-02-23
      相关资源
      最近更新 更多