xamarin - Xamarin Forms View 不使用自定义类更新

标签 xamarin mvvm xamarin.forms prism-6

我正在Xamarin中使用Prism.Unity.Forms进行此项目。当Client.Id属性更改时,如何获取 View 更新?当我将XAML从{Binding Client.Id}(一个Guid对象)更改为{Binding Client.Name}(一个字符串)时, View 更新。

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方法,但是 View 仍然没有更新。
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>

关于xamarin - Xamarin Forms View 不使用自定义类更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45065915/

相关文章:

unit-testing - 为什么我的EventAggregator订阅不处理此事件?

silverlight - 检测 Silverlight 中更改的 DataContext

xamarin.forms - StackLayout 两列,每列占用一半的空间

file - Xamarin 形式 : How to create folder and a file in device external storage?

使用自定义渲染器时未触发 Xamarin Forms Switch 的 Toggled 事件

listview - 所选项目在 ListView 中突出显示 Xamarin.Forms

wpf - 我怎样才能让这个 DataTrigger 工作?

c# - Xamarin Android - OutOfMemoryError 异常 - 大图

c# - Xamarin iOS 内存到处泄漏

ios - IOS Xamarin SQLite 的 JIT 问题