使用命令搜索实现组合框

时间:2016-09-06 11:47:02

标签: c# wpf mvvm

当我使用方法搜索时遇到问题我只得到文本框而不是使用mmvm的组合框这里是我的代码:

在我的构造函数中我有:

  CountryList = new FastObservableCollection<Country>(DummyWebservice.GetCountries());
     SearchCitizenCommand = new RelayCommand(SearchCitizen);

以及展示国家和城市:

   private FastObservableCollection<City> citylist;
        public FastObservableCollection<City> CityList
        {
            get
            {
                return citylist;
            }
            set
            {
                Set(() => CityList, ref citylist, value);


            }
        }


        private FastObservableCollection<Country> countryList;
        public FastObservableCollection<Country> CountryList
        {
            get
            {
                return countryList;
            }
            set
            {
                Set(() => CountryList, ref countryList, value);

            }
        }
        private Country selectedcountry;
        public Country SelectedCountry
        {
            get
            {
                return selectedcountry;
            }

            set
            {
                Set(() => SelectedCountry, ref selectedcountry, value);
                OnPropertyChanged(() => SelectedCity);
                CityList = DummyWebservice.GetCitiesByCountryId(SelectedCountry.Id);

            }
        }
        private City selectedcity;
        public City SelectedCity
        {
            get
            {
                return selectedcity;
            }

            set
            {
                Set(() => SelectedCity, ref selectedcity, value);



            }
        }

并且在我尝试的方法搜索中最终

    SelectedCountry = new Country();
    SelectedCountry.Name = citizen.Citizenship.Name;

在我得到的视图中:

<ComboBox x:Name="txtBirthCountryPicker"
                                  Grid.Row="1"
                                  Grid.Column="1"
                                  HorizontalContentAlignment="Left"
                                  DisplayMemberPath="Name"
                                  ItemsSource="{Binding CountryList}"
                                  SelectedItem="{Binding SelectedCountry}" />

但是我仍然得到它的空虚

2 个答案:

答案 0 :(得分:1)

如果要选择组合中的项目,则需要选择属于ItemsSource的完全相同的对象。

SelectedCountry = CountryList.FirstOrDefault(
   x => x.Name == citizen.Citizenship.Name
)

答案 1 :(得分:0)

Combobox使用对象相等来确定ItemsSource中的哪个项目是所选项目。当您将新的Country实例分配给SelectedItem时,它无法在ItemsSource中找到该国家。

请改为尝试:

SelectedCountry = CountryList.FirstOrDefault(c => c.Name.Equals(citizen.Citizenship.Name, StringComparison.CurrentCultureIgnoreCase);