pass value to label in xaml file from viewmodel

ahmed omar 181 Reputation points
2023-04-10T20:53:41.51+00:00

Hello, I need to change a label text in MAUI xaml file from the SignUpViewModel file . is there any way to do so? in View model I instalized

[ObservableProperty]
        private Label lblEmailDublication;
 [RelayCommand]
         private async void SignUpAsync()
        {
            lblEmailDublication.Text = string.Empty;
}

but once I click on sign up button , I will recieve error System.NullReferenceException: 'Object reference not set to an instance of an object.' lblEmailDublication was null.

Developer technologies .NET .NET MAUI
Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. Lloyd Sheen 1,486 Reputation points
    2023-04-10T21:25:52.73+00:00

    I take it you don't use data binding. Please learn this as it makes Maui development so much easier.
    What you problem is two fold. First the declaration of the Label has no initialization. This is the source of the error as the property has not been initialized. Secondly even if you init the property it will not show in the UI. Learn MVVM and data binding as you will do the following. Rather than have a Label as a property you would have a string as the ObservableProperty. This property will exist in the object which is the BindingContext of the Page/View that hold the Label. The Label will have the following example: <Label Text="{Binding thePropertyWhichHoldsTheString}"> Then when you update the string the UI will get updated.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.