wpf - 将用户控件与 ViewModel 类关联
问题描述
当我定义DataTemplate
内联时,Visual Studio 知道我要绑定的类型,并且该类型中的属性会在自动完成中出现(例如,在下面的代码中,我能够从模板DisplayName
内的自动完成列表中进行选择)。FirstViewModel
<DataTemplate DataType="{x:Type viewmodels:FirstViewModel}">
<StackPanel >
<Label Content="{Binding DisplayName}"/>
</StackPanel>
</DataTemplate>
<DataTemplate DataType="{x:Type viewmodels:SecondViewModel}">
<views:SecondView/>
</DataTemplate>
但是,当数据模板引用外部控件时,如SecondViewModel
在上面的代码中,当我在用户控件的文件中时SecondView
,由于它只是一个控件,因此类型未绑定,编辑器无法帮助我任何事物。
我尝试将我的整个控件(在UserControl
元素内)包装在同一个DataTemplate
标签中,但是我的整个视图只显示“System.Windows.DataTemplate”。
<UserControl x:Class="Gui.Views.Tabs.ExamsTabViews.ExamInfoView"
xmlns:vm="clr-namespace:Gui.ViewModels"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<DataTemplate DataType="vm:ExamInfoViewModel">
<DockPanel VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<!-- contents of the template -->
</DockPanel>
</DataTemplate>
</UserControl>
有没有办法为编辑器实现这种绑定?
解决方案
<DataTemplate DataType="{x:Type viewmodels:SecondViewModel}">
<views:SecondView/>
</DataTemplate>
实例化此 DataTemplate 时,将创建 SecondView,并且该 SecondView 将在 DataContext 中有一个 SecondViewModel。因此 SecondViewModel 控件中不需要任何 DataTemplate - 而是绑定到 DataContext ( {Binding SecondViewModelProperty}
)。要为此类绑定提供设计时支持,请使用d:DataContext="{d:DesignInstance}
:
<UserControl d:DataContext="{d:DesignInstance Type=vm:ExamInfoViewModel,
IsDesignTimeCreatable=True}" ...>
推荐阅读
- elasticsearch - 需要在 ELK 中禁用 x-pack
- mysql-python - 升级到 Ubuntu 20.04 破解 mysqlclient pip 包
- flutter - Flutter 1.17:不再接受小部件列表中的 IF 语句
- powershell - 本地主机 5000 在 windows 中不工作,但所有容器都在 windows 中运行
- ios - 创建 TestFlight 内部测试人员组?
- python - 如何访问定义之外的使用变量?
- javascript - 另一个函数的函数包装器
- javascript - res.send 无法正常运行
- html - 如何在 html 输入中有两种类型
- r - 如何从r中的数据框中提取唯一值