我正在使用 MVVM 构建 WPF 应用程序,但在开发过程中遇到了问题。如何使 ViewModel 类和 xaml 文件一起工作,即,如果 ViewModel 类采用 IUnitOfWork 参数,则将该类作为 DataContext 传递?
ViewModel 类
[INotifyPropertyChanged]
public partial class TeacherViewModel
{
[ObservableProperty]
private ObservableCollection<Teacher> _teachers;
[ObservableProperty]
private Teacher _selectedTeacher;
[ObservableProperty]
private string _firstName;
[ObservableProperty]
private string _lastName;
private IUnitOfWork _unitOfWork;
private ITeacherRepository _teacherRepository;
public TeacherViewModel(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
_teacherRepository = _unitOfWork.TeacherRepository;
_teachers = new ObservableCollection<Teacher>(_teacherRepository.GetAll());
}
}
XAML 文件
<Page x:Class="ProgrammingCourses.Views.Pages.EditTeacher"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:vm="clr-namespace:ProgrammingCourses.ViewModels"
mc:Ignorable="d"
d:DesignHeight="400"
d:DesignWidth="600"
Title="EditTeacher">
<Page.DataContext>
<vm:TeacherViewModel/> <!-- the type "TeacherViewModel" does not include any accessible constructors -->
</Page.DataContext>
...
您可以使用 C# 并从构造函数实例化数据上下文,或使用 XAML 并使用
ObjectDataProvider
: 创建数据上下文实例
EditTeacher.xaml.cs
partial class EditTeacher : Page
{
public EditTeacher()
{
IUnitOfWork unitOfWork = new UnitOfWorkImpl();
var viewModel = new EditTeacherViewModel(unitOfWork);
this.DataContext = viewModel;
InitializeComponent();
}
}
应用程序.xaml
<Application>
<Application.Resources>
<ObjectDataProvider x:Key="EditTeacherViewModelProvider"
ObjectType="{x:Type local:EditTeacherViewModel}">
<ObjectDataProvider.ConstructorParameters>
<local:UnitOfWorkImpl />
</ObjectDataProvider.ConstructorParameters>
</ObjectDataProvider>
</Application.Resources>
</Application>
编辑教师.xaml
<Page DataContext="{Binding Source={StaticResource EditTeacherViewModelProvider}}">
</Page>
如果您使用依赖注入,则必须采取稍微不同的路线。您将使用组合来组合主视图模型类。然后让 IoC 容器导出这个主视图模型。然后视觉根的子元素(或这些元素的
DataContext
)可以引用所需的视图模型类vbia主视图模型。