gpt4 book ai didi

wpf - 将用户控件与 ViewModel 类关联

转载 作者:行者123 更新时间:2023-12-03 10:15:33 24 4
gpt4 key购买 nike

当我定义一个 DataTemplate内联,Visual Studio 知道我要绑定(bind)的类型,并且该类型的属性会在自动完成中出现(例如,在下面的代码中,我能够从 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 的文件中时用户控件,因为它只是一个控件,所以没有绑定(bind)类型,编辑器对我没有任何帮助。

我尝试将整个控件(在 UserControl 元素内)包装在同一个 DataTemplate 中标签,但我的整个 View 只显示“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>

有没有办法为编辑器实现这种绑定(bind)?

最佳答案

<DataTemplate DataType="{x:Type viewmodels:SecondViewModel}">
<views:SecondView/>
</DataTemplate>

实例化此 DataTemplate 时,将创建 SecondView,并且该 SecondView 将在 DataContext 中有一个 SecondViewModel。因此 SecondViewModel 控件中不需要任何 DataTemplate - 而是绑定(bind)到 DataContext ( {Binding SecondViewModelProperty} )。要获得对此类绑定(bind)的设计时支持,请使用 d:DataContext="{d:DesignInstance} :
<UserControl d:DataContext="{d:DesignInstance Type=vm:ExamInfoViewModel, 
IsDesignTimeCreatable=True}" ...>

关于wpf - 将用户控件与 ViewModel 类关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61759878/

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