[英]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
綁定到第一個的SelectedItem
的Cities
屬性:
<ComboBox ItemsSource="{Binding SelectedItem.Cities, ElementName=CmbCountry}"/>
無需在此處設置DisplayMemberPath
,因為Cities
是IEnumerable<string>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.