I’m working on .NET MAUI with MVVM structure. I have a homepage displaying a list of courses. When clicking on a course, I pass a course object to my CourseDetailsViewModel from my startpage.cs.
Now, I have another tab, a registration page, to create new courses. Essentially, both the XAML and ViewModel for registration and editing are the same (same logic). The only difference is that in the ViewModel for editing courses, I receive a course object for data binding to edit properties, while for registration, I bind directly to the properties of courses. Can I create a shared XAML/ViewModel for both registration and editing? Would appreciate a code example on how to approach this.
startpage.cs:
private async void TapGestureRecognizer_Tapped(object sender, TappedEventArgs e)
{
var course = ((VisualElement)sender).BindingContext as Course;
if (course == null) return;
await Shell.Current.GoToAsync(nameof(CourseDetailsPage), true, new Dictionary<string, object>
{{"Course", course}});
}
My ViewModel for editing with a property that’s passed:
[QueryProperty("Course", nameof(Course))]
public partial class CourseDetailsViewModel : BaseViewModel
{
[ObservableProperty]
private Course _course;
}
Details.xaml has Course object with properties:
<DatePicker x:Name="datePicker"
Date="{Binding Course.DateTime}" />
My ViewModel for registration contains properties of the course:
public partial class TripRegistrationViewModel : BaseViewModel
{
[ObservableProperty]
private DateTime _dateTime = DateTime.Now;
[ObservableProperty]
private string _name;
Registration.xaml has properties of Course:
<DatePicker x:Name="datePicker"
Date="{Binding DateTime}" />