Xamarin.forms 如何基于另一个选择器中的选择填充选择器?
我有一个Xamarin.Forms应用程序,它使用FreshMvvm。我有两个选择器控件用于选择国家和州/省。国家的选取者最初是填充的,但州/省的列表应根据所选国家动态填充。我无法找到如何使用命令而不是代码来完成事件处理。 以下是我在MyPage.xaml中的控件:Xamarin.forms 如何基于另一个选择器中的选择填充选择器?,xamarin.forms,freshmvvm,Xamarin.forms,Freshmvvm,我有一个Xamarin.Forms应用程序,它使用FreshMvvm。我有两个选择器控件用于选择国家和州/省。国家的选取者最初是填充的,但州/省的列表应根据所选国家动态填充。我无法找到如何使用命令而不是代码来完成事件处理。 以下是我在MyPage.xaml中的控件: <Picker Title="Choose Country..." ItemsSource="{Binding Countries}" ItemDispl
<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,您可以在任何时候使用
方法,并收听SelectedCountry
属性的更改。发生这种情况时,您将使用所选的国家/地区按国家/地区筛选州/州集合,并使用结果更新您的州/州集合
应该是这样的:
[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);
}
}
[PropertyChanged.AddNotifyPropertyChangedInterface]
公共类MyViewModel:FreshBasePageModel
{
公共可观察收集国家{get;set;}
公共可观测集合状态{get;set;}
//这将是你拥有所有州的收藏
私有列表_allStatesCollection=新列表();
公共国家/地区SelectedCountry{get;set;}
公共MyViewModel()
{
//正在侦听“SelectedCountry”上的更改`
此.WhenAny(OnCountryChanged,o=>o.SelectedCountry);
}
//在“SelectedCountry”属性中设置新值时调用的方法
私有void OnCountryChanged(字符串属性)
{
//筛选状态集合并设置结果
var states=_allStatesCollection.Where(a=>a.CountryCode==SelectedCountry.Code).ToList();
状态=新的可观测集合(状态);
}
}
注意:上面的代码期望您使用Nuget包。如果您不使用它,您可以安装它或实现您的属性PropertyChanged手动。这不会改变代码的其余部分
希望这有帮助-