简体   繁体   English

C# WPF Combobox 选择事件基于从文本文件填充的 Combobox 列表

[英]C# WPF Combobox selection event based on Combobox list populated from text file

I have a Combobox drop down that is populated from a text file.我有一个从文本文件填充的 Combobox 下拉列表。 The combobox is populated with multiple server groups. combobox 填充了多个服务器组。 This is working fine.这工作正常。

servergroups.txt
Group1
Group2
Group3
       public MainWindow()
        {
            InitializeComponent();
            ComboBox2.ItemsSource = File.ReadAllLines(@"c:\temp\servergroups.txt");
        }

The problem i have is that i am also trying to populate a listbox of servers from a server text file based on what server group selected in the combobox.我遇到的问题是,我还试图根据在 combobox 中选择的服务器组从服务器文本文件填充服务器列表框。

group1.txt
server1
server2
server3
        private void ComboBox2_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((ComboBoxItem)ComboBox2.SelectedItem).Content.Equals("Group1"))
            {
                Listbox1.ItemsSource = null;
                Listbox1.Items.Clear();
                Listbox1.ItemsSource = File.ReadAllLines(@"c:\temp\Group1.txt");
                Listbox1.ScrollIntoView(Listbox1.Items[0]);
            }

I am getting the following exception when i select any item from the combobox dropdown当我 select combobox 下拉列表中的任何项目时,我收到以下异常

System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'System.Windows.Controls.ComboBoxItem'.' System.InvalidCastException:“无法将类型为‘System.String’的 object 转换为类型‘System.Windows.Controls.ComboBoxItem’。”

thank you!谢谢你!

The error message clearly says that SelectedItem is of type string .错误消息清楚地表明SelectedItem的类型为string

When you assign a collection of strings to the ItemsSource property of a Selector , the SelectedItem is also a string:当您将字符串集合分配给SelectorItemsSource属性时, SelectedItem也是一个字符串:

if ((string)ComboBox2.SelectedItem == "Group1")
{
    Listbox1.ItemsSource = File.ReadAllLines(@"c:\temp\Group1.txt");
}

In general, the object held by the SelectedItem property is the currently selected element in the Items collection, so that the following condition is true when SelectedIndex >= 0:一般来说, SelectedItem属性持有的object是Items集合中当前选中的元素,所以当SelectedIndex >= 0时,下面的条件为真:

selector.SelectedItem == selector.Items[selector.SelectedIndex]

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

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