我目前正在将信息加载到第二个&第三个组合框取决于我的第一个组合框上的选择。我正在从数组加载信息。它工作正常,但代码集很长。有没有办法使它更整洁,减少代码量。我想到的另一种方法是使用数据绑定和读取。但我无法掌握如何将数组值绑定到组合框的数据。谢谢你的建议。
//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);
}
}
}
答案 0 :(得分:0)
根据Peter的回答,你也可以直接将组合框的ItemsSource绑定到你想要使用的字符串数组。应该看起来像:
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;
}
}
假设这些只是字符串数组,数据绑定应该非常简单。如果不是,你还有一些额外的工作要做。