Jarrad
Jarrad

Reputation: 281

Xamarin.Forms MVVM two way binding between Entry and Property not working(Entry.Text not updated with PropertyChanged)

Problem is solved, creating this since this particular situation is not online.

To clarify, everything was already implemented properly according to Microsoft's Xamarin MVVM documentation at https://learn.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/data-bindings-to-mvvm

The BindingContext, OnAppearing, INotifyPropertyChanged etc. are all perfect.

Situation

  1. I have a picker with a list of Client objects.
  2. I have 4 Entry's, each with two way binding to properties in a Location object. eg.
<Entry x:Name="StreetName_Entry"
       Text="{Binding Location.StreetName, Mode=TwoWay}"/>
  1. When a Client is selected in the Client picker, the program needs to get the Address object that is associated with the Client object, and apply each of the properties in that Address object to the Location object (Address and Location are structurally identical) e.g.
public async void SetLocationAsClientAddress()
        {
            Client client = Client;
            Address clientsAddress;
            if (client != null)
            {
                clientsAddress = await Database.GetAddressFor(client);
                // Location is a property in the ViewModel, as well as an object type
                Location.StreetNumber = clientsAddress.StreetNumber;
                Location.StreetName = clientsAddress.StreetName;
                Location.Suburb = clientsAddress.Suburb;
                Location.Postcode = clientsAddress.Postcode;
            }
        }
  1. Because the Location objects properties are now filled with data, these should immediately display in the 4 Entry.text's because of two way binding. They did not.

Upvotes: 2

Views: 2640

Answers (1)

Jarrad
Jarrad

Reputation: 281

The Solution:

The PropertyChanged event does not trigger when individual properties of an object are edited in the ViewModel. So even though the properties were in fact changed, the View does not know because the event was not fired. So instead of changing individual properties (which is bad practice anyway), use the object's constructor and override the old object with the new one. e.g.

public async void SetLocationAsClientAddress()
        {
            Client client = Client;
            Address clientsAddress;
            if (client != null)
            {
                clientsAddress = await Database.GetAddressFor(client);
                // Location is a property in the ViewModel, as well as an object type
                Location = new Location(0, clientsAddress.StreetNumber, clientsAddress.StreetName, clientsAddress.Suburb, clientsAddress.Postcode);
            }
        }

This way the PropertyChanged event knows that the ViewModel property, which is an object, is different, and lets the View know.

Upvotes: 3

Related Questions