I’m building a WPF application using MVVM, but I ran into a problem during development. How do I make the ViewModel class and the xaml file work together, i.e. pass the class as a DataContext if the ViewModel class takes an IUnitOfWork parameter?
ViewModel class
[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 file
<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>
...
New contributor
Любомир is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.