![](/img/trans.png)
[英]How to re-populate Xamarin Picker based on previous selection from same picker?
[英]How to populate a picker based on selection in another picker?
我有一個 Xamarin.Forms 應用程序,它使用 FreshMvvm。 我有兩個選擇器控件用於選擇國家和州/省。 最初填充國家選擇器,但應根據所選國家動態填充州/省列表。 我找不到如何使用命令而不是代碼隱藏事件處理來完成它。 這是我在MyPage.xaml中的控件:
<Picker Title="Choose Country..."
ItemsSource="{Binding Countries}"
ItemDisplayBinding="{Binding Value}"
SelectedItem="{Binding SelectedCountry}"
Margin="0, 0, 0, 5" />
<Picker Title="Choose State..."
ItemsSource="{Binding States}"
ItemDisplayBinding="{Binding Value}"
SelectedItem="{Binding SelectedState}"
Margin="0, 0, 0, 5" />
我應該在MyPageModel.cs中放什么?
使用 Freshmvvm,您可以使用WhenAny
方法並監聽SelectedCountry
屬性的更改。 發生這種情況時,您將使用 SelectedCountry 按國家/地區過濾州集合,並使用結果更新您的States
集合。
那應該是這樣的:
[PropertyChanged.AddINotifyPropertyChangedInterface]
public class MyViewModel : FreshBasePageModel
{
public ObservableCollection<Country> Countries { get; set; }
public ObservableCollection<State> States { get; set; }
// This would be the collection where you have all the States
private List<State> _allStatesCollection = new List<State>();
public Country SelectedCountry { get; set; }
public MyViewModel()
{
// Listening for changes on the `SelectedCountry`
this.WhenAny(OnCountryChanged, o => o.SelectedCountry);
}
//Method called when a new value is set in the `SelectedCountry` property
private void OnCountryChanged(string property)
{
//Filter the collection of states and set the results
var states = _allStatesCollection.Where(a => a.CountryCode == SelectedCountry.Code).ToList();
States = new ObservableCollection<State>(states);
}
}
注意:上面的代碼希望您使用 Fody INotifyPropertyChanged Nuget package。 如果您不使用它,您可以安裝它或手動實現您的屬性 PropertyChanged。 這不會改變代碼的 rest。
希望這可以幫助。-
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.