【问题标题】:Xamarin Picker not updating after api callapi调用后Xamarin Picker不更新
【发布时间】:2020-05-23 17:03:42
【问题描述】:

我有一个 xamarin 选择器,它应该在从 api(从视图模型内部)获取国家/地区列表后显示国家列表,但是当我将 itemsource 设置为 List 变量时,选择器不会更新。

public Departures(DeparturesViewModel mod)
{
    InitializeComponent();
    model = mod;
    GetCountryData();
}

private async void GetCountryData()
{
    var res= await model.SetCountries();// load api data
    CountryPikcer.IsEnabled = true; 
    CountryPikcer.ItemDisplayBinding = new Binding("Name");//Set the name property as the display property
    CountryPikcer.ItemsSource = model.FilterCountries("");//get loaded List<Country>
}

视图模型:

private List<Country> countries;


public int CountryId
{
    get { return countryId; }
    set { SetProperty(ref countryId, value); }
}

public DeparturesViewModel()
{
    api = new ApiCaller();
    countries = new List<Country>();
}

public async Task<bool> SetCountries()
{
    countries = await api.GetAll<List<Country>>("Countries");
    return true;
}

public List<Country> FilterCountries (string text)
{
    if (text == "")
        return countries;
    List<Country> filtered = countries.Where(x => x.Name.Contains(text)).ToList();
    return filtered;
}

在调试器中填充了 ItemsSource 属性,但选择器不是

【问题讨论】:

  • 发布您的视图模型,更重要的是如何处理项目来源。
  • @Adlorem 添加了视图模型
  • 您用作 ItemSource 的 FilterCountries 方法在哪里?
  • @Jason 它在视图模型中它只是返回 List 属性我无论如何都会添加它
  • 您确定该方法正在返回数据吗? Country 是否包含公共属性“名称”?

标签: xamarin xamarin.forms picker


【解决方案1】:

在我看来,您的问题出在视图模型中。您正在使用异步调用,这意味着您的所有控件都在异步调用的数据可用之前呈现。在这种情况下,您的视图模型应该实现 INotifyPropertyChanged。那么例如:

public List<Country> Countries
{
    {
      set { countries = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Countries))); }
      get { return countries; }    
    }
}

确保控件数据正常刷新。

【讨论】:

    猜你喜欢
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 2020-03-06
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多