c# - 如何在 mvvm 模式中定义用户控件?

标签 c# wpf mvvm user-controls

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

我必须使用 from mvvm 来定义它,还是我可以一般地定义它?

最佳答案

我们只调用嵌入用户控件 MainWindow 和用户控件 UserControl 的控件。由于您处于 MVVM 模式中,因此您至少有一个用于外部 View 的 View 模型——我通常使用名称 MainVm。 对于用户控件,您有两种选择:它们可以共享相同的 View 模型,或者您可以有一个 subview 模型,仅用于 UserControl,即 UserVm。

对于您的第一个选择,您什么都不做。您定义 UserControl(Visual Studio“添加新项目”-> 用户控件是一个很好的开始)。然后,您只需将它嵌入到主窗口中。

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

UserControl 将从 MainWindow 继承相同的 DataContext,并像在 MainWindow 中一样执行所有 {Binding}。

如果您想要一个 subview 模型 (UserVm) - 它通常是 MainVm(例如 userVm)的公共(public)属性。在这种情况下,您将在引用 UserControl 时设置它的 DataContext。

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

另一种流行的范例是声明 DataTemplate 而不是 UserControl。如果这样做,您只需要放置 UserVm(在 XAML 中实例化它,或通过绑定(bind)):

<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>

关于c# - 如何在 mvvm 模式中定义用户控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9544729/

相关文章:

wpf - MVVM 中的绑定(bind) slider 值

c# - 一击将ListView ObservableCollection内的所有项目添加到(WPF Mvvm)

android - 如何使用 Android Jetpack 导航组件在菜单项单击时导航到 fragment

wpf - 将值从 PropertyGrid 控件复制到 Microsoft 扩展 WPF Toolkit™ Community Edition 的剪贴板

c# - 使用 LINQ 和 lambda 将字符串置于正确的大小写形式

c# - 在鼠标悬停时在 C# 表单应用程序中制作文本弹出窗口

C#字符串转句子

c# - 如何在 Pi 的 C# 程序中将小数点精确到 n 位

wpf - 如何删除自定义按钮上的细边框线?

wpf - 没有在 DLL 项目中创建 WPF 窗口?