C# 我可以使用数据绑定从数组中加载值来加载组合框吗
我当前正在将信息加载到第二个和第三个组合框中,具体取决于第一个组合框上的选择。我正在从数组加载信息。它工作正常,但代码集非常长。有没有办法使它更整洁,减少代码量。我想到的另一种方法是使用数据绑定和阅读。但我无法掌握如何将数组值绑定到组合框。谢谢你的建议C# 我可以使用数据绑定从数组中加载值来加载组合框吗,c#,wpf,C#,Wpf,我当前正在将信息加载到第二个和第三个组合框中,具体取决于第一个组合框上的选择。我正在从数组加载信息。它工作正常,但代码集非常长。有没有办法使它更整洁,减少代码量。我想到的另一种方法是使用数据绑定和阅读。但我无法掌握如何将数组值绑定到组合框。谢谢你的建议 //1st combo box name - secondaryTable //2nd combo box name - stCombo1 //3rd combo box name - stCombo2 private void Combo
//1st combo box name - secondaryTable
//2nd combo box name - stCombo1
//3rd combo box name - stCombo2
private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
if (((ComboBoxItem)secondaryTable.SelectedItem).Content.ToString() == "Agents")
{
stCombo1.Items.Clear();
stCombo2.Items.Clear();
foreach (string x in tableArray)
{
stCombo1.Items.Add(x);
stCombo2.Items.Add(x);
}
}
else if (((ComboBoxItem)secondaryTable.SelectedItem).Content.ToString() == "Missions")
{
stCombo1.Items.Clear();
stCombo2.Items.Clear();
foreach (string x in attributeArray)
{
stCombo1.Items.Add(x);
stCombo2.Items.Add(x);
}
}
else
{
stCombo1.Items.Clear();
stCombo2.Items.Clear();
foreach (string x in jobsArray)
{
stCombo1.Items.Add(x);
stCombo2.Items.Add(x);
}
}
}
为了基于Peter的答案,还可以直接将组合框绑定到要使用的字符串数组。应该看起来像:
private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
switch (((ComboBoxItem)secondaryTable.SelectedItem).Content.ToString())
{
case "Agents":
stCombo1.ItemsSource = tableArray;
stCombo2.ItemsSource = tableArray;
break;
case "Missions":
stCombo1.ItemsSource = attributeArray;
stCombo2.ItemsSource = attributeArray;
break;
default:
stCombo1.ItemsSource = jobsArray;
stCombo2.ItemsSource = jobsArray;
break;
}
}
假设这些只是字符串数组,数据绑定应该非常简单。如果不是,你还有一点额外的工作要做