我在这个项目中使用Prism.Unity.Forms和Xamarin。如何让视图在Client.Id
属性更改时进行更新?当我将XAML从{Binding Client.Id}
(一个Guid对象)更改为{Binding Client.Name}
(一个字符串)时,视图就会更新。
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}"/>
我知道将在Client.Id
属性上调用ToString
方法,因为我将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();
}
}
发布于 2017-07-13 12:56:41
使用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>
https://stackoverflow.com/questions/45065915
复制