【问题标题】:C# WPF Combobox selection event based on Combobox list populated from text file基于从文本文件填充的组合框列表的 C# WPF 组合框选择事件
【发布时间】:2023-01-14 01:10:38
【问题描述】:

我有一个从文本文件填充的组合框下拉列表。组合框填充有多个服务器组。这工作正常。

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

我遇到的问题是,我还试图根据在组合框中选择的服务器组从服务器文本文件填充服务器列表框。

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]);
            }

当我从组合框下拉列表中选择任何项目时出现以下异常

System.InvalidCastException:“无法将类型为‘System.String’的对象转换为类型‘System.Windows.Controls.ComboBoxItem’。”

谢谢你!

【问题讨论】:

    标签: c# wpf combobox


    【解决方案1】:

    错误消息清楚地表明SelectedItemstring 类型。

    当您将一组字符串分配给 ItemsControl 的 ItemsSource 属性时,SelectedItem 也是一个字符串:

    if ((string)ComboBox2.SelectedItem == "Group1")
    

    【讨论】:

      猜你喜欢
      • 2020-10-28
      • 2012-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-12
      • 2012-02-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多