【问题标题】:How to populate a picker based on selection in another picker?如何根据另一个选择器中的选择填充选择器?
【发布时间】:2020-07-31 09:52:29
【问题描述】:

我有一个 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 中添加什么?

【问题讨论】:

    标签: xamarin.forms freshmvvm


    【解决方案1】:

    使用 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 包。如果您不使用它,您可以安装它或手动实现您的属性 PropertyChanged。这不会改变其余的代码。

    希望这会有所帮助。-

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-17
      • 2023-03-29
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多