我有一些简单的WinForms代码示例,我试图将其转换为WPF。想法是在选择某个项目时更改ComboBox中的项目,如果发生这种情况,则再次下拉ComboBox。 WinForms代码是:
if (list.Text.Equals("C>>"))
{
comboBox1.Items.Clear();
comboBox1.Items.Add("<<");
comboBox1.Items.Add("C1");
comboBox1.Items.Add("C2");
comboBox1.Items.Add("C3");
comboBox1.Items.Add("C4");
comboBox1.Items.Add("C5");
comboBox1.Items.Add("C6");
comboBox1.DroppedDown = true;
}
虽然我认为这将是一个非常简单的改变,使用
private void hotListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (hotListBox.SelectedItem != null)
{
if (hotListBox.SelectedItem.Equals("b >>"))
{
hotListBox.ItemsSource = secondList;
hotListBox.IsDropDownOpen = true;
}
else if (hotListBox.SelectedItem.Equals("<<"))
{
hotListBox.ItemsSource = initialList;
hotListBox.IsDropDownOpen = true;
}
else if (hotListBox.SelectedItem.Equals("d >>"))
{
hotListBox.ItemsSource = thirdList;
hotListBox.IsDropDownOpen = true;
}
}
}
WPF中的似乎没有以相同的方式工作。我想知道是否有人知道该怎么做?
正如评论中所指出的,我应该说ComboBox中的项目按预期更新,但它不会再次在WPF代码中下拉。
干杯,
编辑:更新的代码
答案 0 :(得分:3)
改变这个:
hotListBox.IsDropDownOpen = true;
到此:
Application.Current.Dispatcher.BeginInvoke(new Action(delegate
{
hotListBox.IsDropDownOpen = true;
}));
答案 1 :(得分:0)
当列表选择发生变化时,更改组合框的项目源可能更容易。
所以创建几个列表
List<string> list1 = new List<string>() { "<<", "C1", "C2", "C3", "C4", "C5", "C6" };
List<string> list2 = new List<string>() { "<<", "f", "g", "h", "i" };
然后只需更改列表选择上的组合框项目源(使用您需要的任何逻辑)
private void _lbTest_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_lbTest.SelectedIndex == 0)
_comboTest.ItemsSource = list1;
else
_comboTest.ItemsSource = list2;
_comboTest.IsDropDownOpen = true;
}