1

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

4

1 回答 1

2

使用 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。这不会改变其余的代码。

希望这可以帮助。-

于 2020-04-17T20:02:03.607 回答