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

问题描述

我正在构建一个wpf应用程序,其中的屏幕将由用于执行各种应用程序的不同用户控件组成.

Hi I am building a wpf application in which a screen will be comprising of different user controls for performing various application.

我想知道在MVVM中执行此操作的正确过程吗?每个用户控件应该拥有自己的视图模型,还是应该绑定到主要的视图模型属性?

I wanted to know the right process for doing this in MVVM? Should each user control have its own view model, or should they still bind to the main View model properties?

请提出一个好的方法.谢谢,

Please suggest a good approach. Thanks,

推荐答案

当我使用UserControl时,我通过DependencyProperties传递了数据.我的UserControls没有ViewModels. UserControls仅以非常特殊的方式处理传递的数据.

When I use an UserControl I pass the data through DependencyProperties. My UserControls doesn't have ViewModels. UserControls only handle the passed data a very special way.

但是,如果我的视图包含一些子视图,则我希望每个子视图都有一个自己的模型.我将通过MainView的ViewModel属性绑定这些模型.

But if I have View that contains some Sub-Views I prefere to have for each Sub-View a own model. These model I'll bind through a property of the ViewModel of the MainView.

一些例子:

UserControl1,代码后面:

UserControl1, Code behind:

public partial class UserControl1 : UserControl
{
    public MyClass MyProperty
    {
        get { return (MyClass)GetValue(MyPropertyProperty); }
        set { SetValue(MyPropertyProperty, value); }
    }

    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.Register("MyProperty", typeof(MyClass), typeof(UserControl1), new UIPropertyMetadata(null));


    public UserControl1()
    {
        InitializeComponent();
    }
}

 public class MyClass
{
    public int MyProperty { get; set; }
}

视图中的用法XAML:

And the usage in the view, XAML:

<Window x:Class="Sandbox.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Sandbox="clr-namespace:Sandbox">
  <Grid>
    <Sandbox:UserControl1 MyProperty="{Binding MyOtherPropertyOfTypeMyClassInMyViewModel, Mode=TwoWay}" />
  </Grid>

希望这会有所帮助

这篇关于如何在WPF MVVM中使用用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 00:04