MVVM: Update the view by modify the model

WhtNs 20 Reputation points
2024-01-16T23:08:43.2533333+00:00

I'm trying to use the MVVM Community Toolkit in my MAUI application. This is my Model

public class InfoModel
{
    public string Name { get; set; }
    public string Address { get; set; }
}

This is my View

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="InfoApp.MainPage"
			 BindingContext="{StaticResource InfoViewModel}">
    <StackLayout>
        <Label Text="{Binding Name}" />
        <Label Text="{Binding Address}" />
    </StackLayout>
</ContentPage>

This is my ViewModel

    public partial class InfoViewModel : ObservableObject
    {
        [ObservableProperty]
        private InfoModel info;

        public InfoViewModel()
        {
            Info = new InfoModel();
        }
    }

The model can be modified not only by the UI, but from data received by a WebSocket. How can I update the model and consequently update the UI?

Thanks

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

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 79,941 Reputation points Microsoft Vendor
    2024-01-17T06:53:46.0933333+00:00

    Hello,

    You can do this by extending ObservableObject for your Model as well. ObservableObject provides a base implementation for INotifyPropertyChanged and INotifyPropertyChanging that could make your property in the Model update at the runtime.

    public class InfoModel: ObservableObject
    {
        private string name;
       public string Name
        {
            get => name;
            set => SetProperty(ref name, value);
        }
       private string address;
       public string Address
        {
            get => address;
            set => SetProperty(ref address, value);
        }  
    }
    

    After receiving the data from the WebSocket. You can set the value to the Info object directly with Info.Address = "Your Address from WebSocket"; or Info.Name="your name from the WebSocket" in your Viewmodel.

    Best Regards, Leon Lu


    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

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.