.net - 如何在 WPF MVVM 中使用用户控件

标签 .net wpf mvvm wpf-controls binding

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

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

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

最佳答案

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

但是,如果我有包含一些 subview 的 View ,我希望每个 subview 都有一个自己的模型。这些模型我将通过 MainView 的 ViewModel 的一个属性进行绑定(bind)。

一些例子:

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

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

希望这可以帮助

关于.net - 如何在 WPF MVVM 中使用用户控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6841924/

相关文章:

c# - 如何避免 RCW 清理上的竞争

c# - WPF 将 ObservableCollection 绑定(bind)到 UserControl 的意外行为

c# - 函数运行时用于显示图片的线程

ios - ReactiveX,关于移动应用架构和层

c# - 我该如何缩短 If else

.net - 在Visual Studio 2010解决方案级别定位特定版本的.NET框架

c# - 有关在.NET中调用分布式系统的批处理建议

wpf - Silverlight 3 中 ItemContainerStyle 中的数据绑定(bind)问题

c# - XAML 将 Rectange.Fill SolidColorBrush 绑定(bind)到 Color 属性

asp.net-mvc - 在MVVM详细信息 View 中使用其他表