繁体   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#

我有两个组合框,一个显示国家数据,第二个显示城市。

我正在使用来自 JSON 文件的反序列化数据绑定这些 combobox:

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

反序列化它并像这样提取数据:

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 { }
  }
}

最后将它绑定到组合框,如下所示:

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

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

此过程的结果是“国家”combobox 最终被填充,而“城市”combobox 显示一系列标记为(集合)的项目。

这是两种场景的屏幕截图。 “国家”组合框显示

“城市”组合框显示

我想要的是“城市”combobox 显示附加到“国家”combobox 的各个城市。

我在做什么/我在哪里/哪里出错了,我该如何补救?

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

或者更常见的是,您的虚拟机上只有一个SelectedCountry 例如

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

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

您的AllCountriesData.City最好命名为AllCountriesData.Cities ,因为它是多个城市的集合。

将第二个ComboBox绑定到第一个的SelectedItemCities属性:

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

无需在此处设置DisplayMemberPath ,因为CitiesIEnumerable<string>

暂无
暂无

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

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