从运行时添加的列表框项中获取字符串

Getting a string from a listbox item added during runtime

我有一个列表框,上面有一个项目,然后它可以被从文本框中输入的文本中提取的几个项目(单词)替换。它们添加了 listbox.Items.Add(word)。 我希望能够在选择这些单词时将它们从列表框中转换回字符串(这样我就可以用它们做其他事情)但是我遇到了两个我不确定如何处理的问题:

  1. 选择原始项目时出现异常:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

使用时 string s = ((ListBoxItem)listbox.SelectedItem).Content.ToString();

"System.NullReferenceException: 'Object reference not set to an instance of an object.'

System.Windows.Controls.Primitives.Selector.SelectedValue.get returned null."

使用 string s = listbox.SelectedValue.ToString();

  1. When any of the new items are selected nothing happens.我认为这是因为事件处理程序仅附加到列表中开始时的单个项目,但我不确定如何将其应用于尚不存在的项目。选择列表框中的任何项目时是否有事件处理程序?

如有任何帮助,我们将不胜感激,提前致谢。

你可以试试这个,你可以测试列表框中元素的选择:

 private void youListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     if(yourListBox.SelectedItem != null)
     {
        ....
     }
 }

您应该收听 SelectionChanged 事件。见下文

        public MainWindow()
        {
            InitializeComponent();

            ListBox.Items.Add("Word1");
            ListBox.Items.Add("Word2");
            ListBox.Items.Add("Word3");
            ListBox.Items.Add("Word4");

            ListBox.SelectionChanged += ListBox_SelectionChanged;
        }

        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var listBoxValue = ListBox.SelectedValue.ToString();
            Console.WriteLine(listBoxValue);
        }