Is it possible to make a label update as soon as a variable changes?

Mielesplayz 281 Reputation points
2022-09-05T09:15:58.25+00:00

I want to update the text on a label as soon as the variable connected to it updates.
And if possible I want to avoid making loops to save resources.

(For example: I have a string which shows your username on it, and when you change your username in the settings I want it to also update on the label)

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,900 questions
0 comments No comments
{count} votes

Accepted answer
  1. Wenyan Zhang (Shanghai Wicresoft Co,.Ltd.) 26,446 Reputation points Microsoft Vendor
    2022-09-06T09:15:45.64+00:00

    Hello @Mielesplayz ,

    You could try using interactive MVVM and data bindings. Viewmodels typically implement the INotifyPropertyChanged interface, which provides the ability for a class to raise the PropertyChanged event whenever one of its properties changes. The data binding mechanism in .NET MAUI attaches a handler to this PropertyChanged event so it can be notified when a property changes and keep the target updated with the new value.
    For more information, please see: Data binding basics - .NET MAUI | Microsoft Learn
    Data binding and MVVM - .NET MAUI | Microsoft Learn

    You can also refer to the sample :

    1. Set binding context for the page, see the source code here.
    2. Add the Label whose Text property is bound to the DisplayText property of KeypadViewModel , see the source code here.
    3. The KeypadViewModel needs to implement the the INotifyPropertyChanged interface, you can refer to the usage of DisplayText property. If you have a model to provide this property, please check the Use pass-through properties with a viewmodel part in learning modules .

    The sample shows how the InputString changes when the AddCharCommand / DeleteCharCommand is triggered, and the DisplayText will be updated in the set method of InputString . You can update the UserName property of your VM, the Label(element is bound to UserName) will be updated as well.

    In addition, you can see the MVVM part in books. The doc is about Xamarin, it's old, but still conceptually valid.

    Best Regards,
    Wenyan Zhang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful