Xamarin窗体视图不会更新自定义类
问题描述:
我使用Prism.Unity.Forms与Xamarin这个项目。如何在Client.Id
属性更改时更新视图?当我将{Binding Client.Id}
(Guid对象)的XAML更改为{Binding Client.Name}
(字符串)时,视图更新。Xamarin窗体视图不会更新自定义类
public class CreateClientViewModel : BindableBase
{
private Client _client;
public Client Client {
get => _client;
set => SetProperty(ref _client, value);
}
private async void FetchNewClient()
{
Client = new Client{
Id = new Guid.Parse("501f1302-3a45-4138-bdb7-05c01cd9fe71"),
Name = "MyClientName"
};
}
}
这工作
<Entry Text="{Binding Client.Name}"/>
这不
<Entry Text="{Binding Client.Id}"/>
我知道ToString
方法被调用的Client.Id
属性,因为我在一个自定义类包裹Guid
和重载了ToString
方法,但该视图仍然不更新。
public class CreateClientViewModel : BindableBase
{
private Client _client;
public Client Client {
get => _client;
set => SetProperty(ref _client, value);
}
//This method will eventually make an API call.
private async void FetchNewClient()
{
Client = new Client{
Id = new ClientId{
Id = new Guid.Parse("501f1302-3a45-4138-bdb7-05c01cd9fe71")
},
Name = "MyClientName"
};
}
}
public class ClientId
{
public Guid Id { get; set }
public override string ToString()
{
//This method gets called
Console.WriteLine("I GET CALLED");
return Id.ToString();
}
}
答
使用Converter
解决了这个问题,但我无法解释为什么。两种方法都被称为Guid.ToString
方法。
<Entry Text="{Binding Client.Id, Converter={StaticResource GuidConverter}}"/>
public class GuidConverter : IValueConverter
{
public object Convert()
{
var guid = (Guid) value;
return guid.ToString();
}
public object ConvertBack(){...}
}
然后我注册的转换器在App.xaml
<ResourceDictionary>
<viewHelpers:GuidConverter x:Key="GuidConverter" />
</ResourceDictionary>
务必使您的客户端执行INotifyPropertyChanged –