繁体   English   中英

Xamarin.Forms MVVM 在 Entry 和 Property 之间的双向绑定不起作用(Entry.Text 未使用 PropertyChanged 更新)

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

问题已解决,创建此问题是因为此特定情况不在线。

为了澄清,一切都已经根据微软的 Xamarin MVVM 文档在https: //docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/data-bindings-to-mvvm 正确实施

BindingContext、OnAppearing、INotifyPropertyChanged 等都是完美的。

情况

  1. 我有一个带有 Client 对象列表的选择器。
  2. 我有 4 个条目,每个条目都有两种方式绑定到位置 object 中的属性。 例如。
<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) eg
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. 因为 Location 对象属性现在填充了数据,这些应该立即显示在 4 Entry.text 中,因为有两种方式绑定。 他们没有。

解决方案:

在 ViewModel 中编辑 object 的各个属性时,不会触发 PropertyChanged 事件。 因此,即使属性实际上已更改,视图也不知道,因为未触发事件。 因此,不要更改单个属性(无论如何这都是不好的做法),而是使用对象的构造函数并用新的 object 覆盖旧的 object。 例如

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);
            }
        }

通过这种方式,PropertyChanged 事件知道 ViewModel 属性(即 object)是不同的,并让 View 知道。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM