如何定义MVVM模式的用户控件? [英] How to define the usercontrols in mvvm pattern?

查看:249
本文介绍了如何定义MVVM模式的用户控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从MVVM在我的应用程序中使用。我想知道如何定义在MVVM模式我的用户控件。

I using from mvvm in my application. I want know how to define my user control in mvvm pattern.

我必须从MVVM使用定义它,或者我可以大致界定呢?

Must I define it by using from mvvm, or I can define it generally?

推荐答案

让我们只需要调用嵌入用户控件主窗口的控制,以及用户控件用户控件。既然你在MVVM模式,你必须为外部视图至少一个视图模型 - 我通常使用的名称MainVm。
你必须为用户控件两个选择:他们可以共享同一个视图模型,或者你可以有一个子视图模型,只是为用户控件,即UserVm

Let's just call the control that embeds the user control MainWindow, and the user control UserControl. Since you are in MVVM pattern, you have at least one View Model for the outer view - I usually use the name MainVm. You have two choices for the user control: They can share the same View Model, or you could have a sub view model, just for the UserControl, i.e. UserVm.

有关您的第一选择,你什么都不做。您可以定义用户控件(Visual Studio的添加新项 - >用户控制是一个不错的开始)。然后,你只需将它嵌入到主窗口。

For your first choice, you do nothing. You define UserControl (Visual Studio 'add new item' -> User Control is a pretty good start). Then, you simply embed it in Main Window.

<Window
    x:Class="SO.MainWindow"
    ...
    xmlns:src="clr-namespace:SO"
    ...
    >
    ...
    <src:UserControl />
    ...
</Window>



用户控件将继承主窗口相同的DataContext,做所有的{结合},你会在做。在主窗口

UserControl will inherit the same DataContext from MainWindow, and do all the {Binding} as you would do in the MainWindow.

如果你想有一个子视图模型(userVm) - 这通常是MainVm(比如,userVm)的公共属性。在这种情况下,你会设定,当你引用它的用户控件的DataContext的

If you want to have a sub view model (UserVm) - it would typically be a public property of the MainVm (say, userVm). In that case, you'll set the DataContext of the UserControl when you reference it.

<src:UserControl DataContext="{Binding Path=userVm}" />



另一种流行的模式将是宣布DataTemplate中,而不是用户控件的。如果你这样做,你只是需要把UserVm(或者初始化它在XAML,或通过绑定):

Another popular paradigm would be to declare the DataTemplate instead of the UserControl. If you do that, you just need to put the UserVm (either instantiate it in the XAML, or through binding):

<Window x:Class="MainWindow" ...>
    <Window.Resources>
        <DataTemplate x:Key="UserDt">   <!-- or user TargetType instead of x:Key -->
            ...
        </DataTemplate>
    </Window.Resources>

    ...

    <!-- You can put in a ContentControl like here: -->
    <ContentControl Content="{Binding Path=userVm}" 
                    ContentTemplate="{StaticResource UserDt}" />

    <!-- or, if you defined TargetType for the DT, you can simply instantiate
         the sub VM here. I don't like this apporach but it exists. -->
    <src:UserVm />
</Window>

这篇关于如何定义MVVM模式的用户控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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