r/dotnetMAUI•
PMental

MVVM problems, having troubles with data bindings getting the UI to update properly.

Help Request

Hi! I'm having trouble with getting my UI to update when things change behind the scenes.

Basically it seems INotifyPropertyChanged really doesn't like me.

I've tried tons of variants from StackOverflow, samples etc. but nothing seems to work. Eg. I tried using the the methods in this tutorial video (project code here) and while it works when using it exactly as he does, it doesn't work the way I actually need it to.

Here's an example (using the Community Toolkit like in the video above):

MainPage.xaml

<?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="UpdatedBindingText.MainPage"
            xmlns:viewmodel="clr-namespace:UpdatedBindingText"
            x:DataType="viewmodel:ModelClass">
    <VerticalStackLayout>
        <Label x:Name="Label" Text="{Binding Name}" HorizontalTextAlignment="Center"></Label>
        <Button 
            Command="{Binding UpdateTextCommand}"
            CommandParameter="Two!"
            Text="Two">
        </Button>
        <Button 
            Clicked="ThirdButtonClick"
            Text="Three!">
        </Button>
    </VerticalStackLayout>
</ContentPage>

MainPage.xaml.cs

namespace UpdatedBindingText;
using System.Diagnostics;
public partial class MainPage: ContentPage {
    ModelClass myModel = new();
    public MainPage(ModelClass model) {
        InitializeComponent();
        BindingContext = model;
    }
    private void ThirdButtonClick (object sender, EventArgs e) {
        myModel.UpdateAgain("Third");
        myModel.Name = "Third I said!";
        myModel.UpdateText("THIIIIRD!");
        Debug.WriteLine($"myModel value is: {myModel.Name}");
    }
}

ModelClass.cs

namespace UpdatedBindingText;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

public partial class ModelClass : ObservableObject {
    [ObservableProperty]
    static string name = "One";

    [RelayCommand]
    public void UpdateText(string labelValue) {
        Name = labelValue;
    }
    public void UpdateAgain(string Third) {
        UpdateText(Third);
        Name = Third;
    }
}

The button that binds to the RelayCommand works fine, updates the label to "Two", the other button does not though. The code runs, the Name property updates, but the label does not update, presumably because it fails to trigger the change notification for whatever reason. I've tried a bunch of variants as you can see, but nothing, only the "Two" button works.

Where am I going wrong? Why won't any updates trigger the change?

Posted Jan 4, 2023, 6:11 PM UTC

314
Loading comments…