Xamarin Picker 在 api 调用后未更新
Xamarin Picker not updating after api call
我有一个 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 属性 正在填充,但选择器不是
我认为您的问题出在视图模型中。您正在使用异步调用,这意味着您的所有控件都在异步调用的数据可用之前呈现。在这种情况下,您的视图模型应该实现 INotifyPropertyChanged。那么例如:
public List<Country> Countries
{
{
set { countries = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Countries))); }
get { return countries; }
}
}
确保控件数据正确刷新。
我有一个 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 属性 正在填充,但选择器不是
我认为您的问题出在视图模型中。您正在使用异步调用,这意味着您的所有控件都在异步调用的数据可用之前呈现。在这种情况下,您的视图模型应该实现 INotifyPropertyChanged。那么例如:
public List<Country> Countries
{
{
set { countries = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Countries))); }
get { return countries; }
}
}
确保控件数据正确刷新。