如何在WPF MVVM中使用用户控件

gan*_*ran 9 .net wpf binding mvvm wpf-controls

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

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

请建议一个好的方法.谢谢,

Wal*_*tiD 5

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

但是,如果我有包含一些子视图的视图,我优先为每个子视图创建一个自己的模型.这些模型我将通过MainView的ViewModel的属性进行绑定.

一些例子:

UserControl1,代码落后:

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; }
}
Run Code Online (Sandbox Code Playgroud)

和视图中的用法,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>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助