Home > Net >  .NET MAUI Data binding and MVVM
.NET MAUI Data binding and MVVM

Time:02-10

This seems so straightforward, but i can't get it to working properly. The simplest MAUI app with a Label binding to "CountDisplay" and a Button binding to "IncreaseCount". The Command binding works, the Label binding reads the first time its value but then never refreshes. What i'm doing wrong ? Thanks for any help.

MainPage.xaml

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="MauiApp1.MainPage"
         BackgroundColor="{DynamicResource SecondaryColor}">

<ScrollView>
    <Grid RowSpacing="25" RowDefinitions="Auto,Auto,Auto,Auto,*"
          Padding="{OnPlatform iOS='30,60,30,30', Default='30'}">

         <Label 
            Text="{Binding CountDisplay}"
            Grid.Row="2"
            FontSize="18"
            FontAttributes="Bold"
            HorizontalOptions="Center" 
            />

        <Button 
            Text="Click me"
            FontAttributes="Bold"
            Grid.Row="3"
            SemanticProperties.Hint="Counts the number of times you click"
            Command="{Binding IncreaseCount}"
            HorizontalOptions="Center" />

    </Grid>
    
    
</ScrollView>

MainPageViewModel.cs

public class MainPageViewModel:BindableObject   
{
    public MainPageViewModel()
    {
        IncreaseCount = new Command(OnIncrease);
    }
    public ICommand IncreaseCount { get; }

    int count = 0;
    string countDisplay = "Click Me()!";

    public string CountDisplay
    {
        get { return countDisplay; }

        set
        {
            if (value == countDisplay)
                return;

            countDisplay = value;
            OnPropertyChanged();
            
        }
    }

    void OnIncrease()
    {
        count  ;
        countDisplay = $"Current count: {count}";
    }
}

CodePudding user response:

you are setting the private variable (lowercase "c")

void OnIncrease()
{
    count  ;
    countDisplay = $"Current count: {count}";
}

instead, you need to set the public property (upper case "C"), otherwise OnPropertyChanged is not called

void OnIncrease()
{
    count  ;
    CountDisplay = $"Current count: {count}";
}

a popular convention is to name the private variable with an _ so that the two names are harder to mix up (_countDisplay and CountDisplay)

  •  Tags:  
  • Related