2017-07-12 50 views
1

我使用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(); 
    } 
} 
+0

務必使您的客戶端執行INotifyPropertyChanged –

回答

0

使用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>