简体   繁体   English

Bind a WPF ComboBox Based on Data From Another ComboBox Using JSON in C#

[英]Bind a WPF ComboBox Based on Data From Another ComboBox Using JSON in C#

I have two comboboxes, one displays the country data, while the second displays cities.我有两个组合框,一个显示国家数据,第二个显示城市。

I am binding these combobox using deserialized data from a JSON file structured this way:我正在使用来自 JSON 文件的反序列化数据绑定这些 combobox:

 [ { "country": "Albania", "city": [ "Elbasan", "Petran", "Pogradec", "Shkoder", "Tirana", "Ura Vajgurore" ] } ]

Deserializing it and extracting the data like this:反序列化它并像这样提取数据:

public partial class SomeUCClass: UserControl
{      
    readonly UtilityMethods utilityMethods = new UtilityMethods();

    private string jsonFilePath = @"C:\SomePath\CountryData.json";

    public ObservableCollection<AllCountriesData> countryCityData { get; set; }

    public SomeUCClass()
    {
        InitializeComponent();
        countryCityData = new ObservableCollection<AllCountriesData>();
        DataContext = this;
    }

    private void SomeUCClass_Loaded(object sender, RoutedEventArgs e)
    {
        try
        {
            using (StreamReader streamReader = new StreamReader(jsonFilePath))
            {
                string actualJsonFile = streamReader.ReadToEnd();
                var x = JsonConvert.DeserializeObject<List<AllCountriesData>>(actualJsonFile);
                foreach (var countryCityDataObject in x)
                {
                    countryCityData.Add(new AllCountriesData() { Country = countryCityDataObject.Country, Cities = new ObservableCollection<string>() { countryCityDataObject.MyString.ToString() } });
                }

            }
        }
        catch (Exception ex)
        {
            utilityMethods.ErrorMessage(ex.Message);
        }


    }


  }

public class AllCountriesData
{
  public string Country { get; set; }
  public ObservableCollection<string> Cities { get; set; }
  public string MyString
  {
     get { return Convert.ToString(Cities); }
     set { }
  }
}

Finally binding it to the comboboxes like so:最后将它绑定到组合框,如下所示:

<ComboBox x:Name="CmbCountry" 
          ItemsSource="{Binding countryCityData}" 
          DisplayMemberPath="Country"/>

<ComboBox x:Name="CmbCities" 
          ItemsSource="{Binding countryCityData}"
          DisplayMemberPath="Cities"/>

The results of this process is that the "Country" combobox ends up being populated, while the "City" combobox displays a series of items labelled (Collection).此过程的结果是“国家”combobox 最终被填充,而“城市”combobox 显示一系列标记为(集合)的项目。

Here's the screenshots of both scenarios.这是两种场景的屏幕截图。 “国家”组合框显示

“城市”组合框显示

What I'd like is for the "Cities" combobox to display the respective cities attached to the "Country" combobox.我想要的是“城市”combobox 显示附加到“国家”combobox 的各个城市。

What/Where I'm I doing/going wrong and how can I remedy this?我在做什么/我在哪里/哪里出错了,我该如何补救?

<ComboBox ItemsSource="{Binding SelectedItem.City, ElementName=CmbCountry}"/>

Or more usually you would just have a SelectedCountry on your VM.或者更常见的是,您的虚拟机上只有一个SelectedCountry eg例如

<ComboBox ItemsSource="{Binding countryCityData}" 
          DisplayMemberPath="Country" 
          SelectedItem="{Binding SelectedCountry}"/>

<ComboBox ItemsSource="{Binding SelectedCountry.City}" 
          SelectedItem="{Binding SelectedCity}"/>

Your AllCountriesData.City would be better named AllCountriesData.Cities since it it a collection of multiple cities.您的AllCountriesData.City最好命名为AllCountriesData.Cities ,因为它是多个城市的集合。

Bind the second ComboBox to the Cities property of the SelectedItem of the first one:将第二个ComboBox绑定到第一个的SelectedItemCities属性:

<ComboBox ItemsSource="{Binding SelectedItem.Cities, ElementName=CmbCountry}"/>

There is no need to set the DisplayMemberPath here since Cities is an IEnumerable<string> .无需在此处设置DisplayMemberPath ,因为CitiesIEnumerable<string>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM