将用户控件与 ViewModel 类关联 [英] Associate User Control with ViewModel class

查看:26
本文介绍了将用户控件与 ViewModel 类关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我定义一个 DataTemplate 内联时,Visual Studio 知道我要绑定到的类型,并且该类型中的属性会在自动完成中出现(例如在下面的代码中,我能够选择DisplayName 来自 FirstViewModel 模板内的自动完成列表).

When I define a DataTemplate inline, Visual Studio knows about the type I'm binding to, and properties in that type come up in autocomplete (for example in the code below I was able to select DisplayName from the autocomplete list inside the FirstViewModel template).

<DataTemplate DataType="{x:Type viewmodels:FirstViewModel}">
    <StackPanel >
        <Label Content="{Binding DisplayName}"/>
    </StackPanel>
</DataTemplate>

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

但是,当数据模板引用外部控件时,对于上面代码中的SecondViewModel,当我在SecondView 用户控件的文件中时,因为它是只是一个控件,类型没有绑定,编辑器也没有帮助我做任何事情.

However, when the data template references an external control, as for SecondViewModel in the code above, when I'm in the file for the SecondView usercontrol, since it's just a control, the type isn't bound and the editor doesn't help me with anything.

我尝试将整个控件(在 UserControl 元素内)包装在同一个 DataTemplate 标记中,但随后我的整个视图只显示System.Windows.DataTemplate".

I've tried wrapping my whole control (inside the UserControl element) in the same DataTemplate tag, but then my whole view just shows "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>

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

Is there a way to achieve this kind of binding for the editor?

推荐答案

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

当这个DataTemplate被实例化时,会创建SecondView,并且SecondView在DataContext中会有一个SecondViewModel.所以在 SecondViewModel 控件中不需要任何 DataTemplate - 而是绑定到 DataContext ({Binding SecondViewModelProperty}).要在设计时支持此类绑定,请使用 d:DataContext="{d:DesignInstance}:

when this DataTemplate is instantiated, there will be created SecondView and that SecondView will have a SecondViewModel in DataContext. So there is no need any DataTemplate in SecondViewModel control - bind to DataContext instead ({Binding SecondViewModelProperty}). To have design-time support for such binding use d:DataContext="{d:DesignInstance}:

<UserControl d:DataContext="{d:DesignInstance Type=vm:ExamInfoViewModel, 
                             IsDesignTimeCreatable=True}" ...>

这篇关于将用户控件与 ViewModel 类关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆