Die Views sind die visuelle Komponente der App und zeigen die Daten aus dem gebundenen ViewModel an. Der Ctor der Inhaltsseite muss als Parameter das ViewModel akzeptieren, wie das folgende Beispiel zeigt.
public partial class DashboardPage : ContentPage
{
public DashboardPage(DashboardPageViewModel viewModel)
{
InitializeComponent();
BindingContext = viewModel;
Loaded += ((DashboardPageViewModel)BindingContext).Pages_Loaded;
}
~DashboardPage()
{
Loaded -= ((DashboardPageViewModel)BindingContext).Pages_Loaded;
}
#region Methods
protected override void OnAppearing()
{
base.OnAppearing();
try
{
((DashboardPageViewModel)BindingContext).OnAppearing();
}
catch (Exception) { }
}
protected override void OnDisappearing()
{
base.OnDisappearing();
try
{
((DashboardPageViewModel)BindingContext).OnDisappearing();
}
catch (Exception) { }
}
#endregion
}Somit weis die View, welches ViewModel sich dahinter verbirgt. Zusätzlich sollte auch in der Xaml-Ansicht auf das richtige ViewModel verwiesen werden.
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="AppBasement.Views.DashboardPage"
xmlns:localization="clr-namespace:AppBasement.Resources.Localization"
xmlns:viewModels="clr-namespace:AppBasement.ViewModels"
Title="{x:Static localization:Strings.Dashboard}"
Style="{StaticResource DefaultPageStyle}"
x:DataType="viewModels:DashboardPageViewModel"
>
<!-- Some content -->
</ContentPage>Dies hat den Vorteil, dass schon beim Erstellen des Projektes geprüft wird, ob die Bindings der View auch im ViewModel verfügbar sind. Das erleichtert das spätere Fehlersuchen und verbessert die Performance der App.