Dot-Net

如何在 WPF MVVM 中使用使用者控制項

  • July 28, 2011

您好我正在建構一個 wpf 應用程序,其中一個螢幕將包含用於執行各種應用程序的不同使用者控制項。

我想知道在 MVVM 中執行此操作的正確過程?每個使用者控制項應該有自己的視圖模型,還是應該綁定到主視圖模型屬性?

請提出一個好的方法。謝謝,

當我使用 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; }
}

以及視圖中的用法,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>

希望這可以幫助

引用自:https://stackoverflow.com/questions/6841924