首页 > 解决方案 > 将用户控件与 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>

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

标签: wpfxamlmvvm

解决方案


<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}" ...>

推荐阅读