gpt4 book ai didi

c# - 如何根据用户选择动态注入(inject)用户控件

转载 作者:太空狗 更新时间:2023-10-30 01:09:43 26 4
gpt4 key购买 nike

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

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

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

编辑

这就是我认为 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>

这是一个示例 View 模型。

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

然后把它们粘在一起

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

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

希望这对某人有帮助。

最佳答案

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

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

关于c# - 如何根据用户选择动态注入(inject)用户控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6156151/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com