我在我的应用程序中使用了 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/