wpf 使用 Mvvm 时将数据上下文视图模型绑定到用户控件视图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36778194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Binding datacontext viewmodel to usercontrol view when using Mvvm
提问by Mikkel
I need some help binding the viewModel to the two usercontrol views I have created.
我需要一些帮助将 viewModel 绑定到我创建的两个用户控件视图。
Have created a Reservation Window that should contain these two usercontrols.
创建了一个应包含这两个用户控件的 Reservation Window。
What i got:
我得到了什么:
- ReservationView (Window)
- ReservationListView (Usercontrol)
- ReservationDetailView (Usercontrol)
- 预订视图(窗口)
- ReservationListView(用户控件)
- ReservationDetailView(用户控件)
ReservationView (Window) class
ReservationView(窗口)类
public partial class ReservationView : Window
{
public ReservationView()
{
InitializeComponent();
//DataContext = null;
}
}
ReservationListView (Usercontrol) class:
ReservationListView(用户控件)类:
public partial class ReservationListView : UserControl, IViewReservationListViewModel
{
public ReservationListView(IViewReservationListViewModel viewModel)
{
InitializeComponent();
DataContext = viewModel;
}
}
The IViewReservationListViewModel is just a empty interface which makes the contact between the usercontrol view and the viewModel.
IViewReservationListViewModel 只是一个空接口,它在用户控件视图和视图模型之间建立联系。
ReservationListViewModel
预留列表视图模型
public class ReservationListViewModel : INotifyPropertyChanged, IViewReservationListViewModel
{
public ReservationListViewModel()
{
}
}
When I try to set the local:"usercontrol" in the xaml inside ReservationView, I get the following error:
当我尝试在 ReservationView 内的 xaml 中设置 local:"usercontrol" 时,出现以下错误:
The type "ReservationListView" does not include any accessible constructors.
How should I link those two usercontrol to the respective viewModels when I use MVVM?
当我使用 MVVM 时,我应该如何将这两个用户控件链接到各自的视图模型?
回答by Clemens
You would usually have a MainViewModel like
你通常会有一个 MainViewModel 像
class MainViewModel
{
public ReservationListViewModel ReservationListViewModel { get; set; }
public ReservationDetailViewModel ReservationDetailViewModel { get; set; }
}
and would use it in your XAML like
并将在您的 XAML 中使用它,例如
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
<local:ReservationListView DataContext="{Binding ReservationListViewModel}"/>
<local:ReservationDetailView DataContext="{Binding ReservationDetailViewModel}"/>
Your UserControls wouldn't need any constructors with parameters.
您的 UserControls 不需要任何带参数的构造函数。

