【问题标题】:Xamarin Forms View Does Not Update With Custom ClassXamarin 表单视图不会随自定义类更新
【发布时间】:2017-07-12 19:20:08
【问题描述】:

我在这个项目中使用 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();
    }
}

【问题讨论】:

  • 一定要让你的客户端实现 INotifyPropertyChanged

标签: xamarin mvvm xamarin.forms prism-6


【解决方案1】:

使用Converter 解决了这个问题,但我无法解释原因。 Guid.ToString 方法正在被调用。

&lt;Entry Text="{Binding Client.Id, Converter={StaticResource GuidConverter}}"/&gt;

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 2018-09-18
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多