![](/img/trans.png)
[英]Xamarin.Forms Data bind Button.CommandParameterProperty to Entry.Text in Code Behind
[英]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 等都是完美的。
情况
<Entry x:Name="StreetName_Entry"
Text="{Binding Location.StreetName, Mode=TwoWay}"/>
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;
}
}
解决方案:
在 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.