简体   繁体   English

选择项目列表框C#

[英]select item listbox c#

I'm trying to use C# to select an item in a listbox using a switch statement but nothing happens: 我正在尝试使用C#使用switch语句在列表框中选择一个项目,但没有任何反应:

This is my current code: 这是我当前的代码:

XAML XAML

<ListBox x:Name="test" (XAML OMITED) SelectionChanged="test_SelectionChanged">
 <ListBoxItem Content="name 1" />

c# C#

 private void test_SelectionChanged(object sender,  System.EventArgs e)
    {
        switch (test.SelectedItem.ToString())
        {
            case "name 1":
                MessageBox.Show("X");
                break;
            case "name 2":
                MessageBox.Show("X");
                break;
            default:

                break;
        }

thanks 谢谢

The listbox is the sender object so you can access it like so. 列表框是发件人对象,因此您可以像这样访问它。 You just need to cast the sender as a listbox, then your selected item is a listbox item so you would cast it and then you can access the content values. 您只需要将发件人转换为列表框,然后您选择的项目就是一个列表框项目,因此您将其进行转换然后可以访问内容值。 Also when I created my selectionchanged event handler it accepts SelectionChangedEventArgs e not System.EventArgs e, SelectionChangedEventArgs is found in the System.Windows.Controls Namespace, which should already be imported into your class through using statement. 同样,当我创建我的selectionchanged事件处理程序时,它接受SelectionChangedEventArgs(而不是System.EventArgs),在System.Windows.Controls命名空间中找到SelectionChangedEventArgs,应该已经使用using语句将其导入到您的类中。

var mySender = (ListBox)sender;
swtich(((ListBoxItem)mySender.SelectedItem).Content.ToString()){

  case "name 1":
            MessageBox.Show("X");
            break;
  case "name 2":
            MessageBox.Show("X");
            break;
  default:
            break;
}
 private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            foreach (var selectedItem in e.AddedItems)
            {
                switch ((selectedItem as ListBoxItem).Content.ToString())
                {
                    case "name 1":
                        MessageBox.Show("X");
                        break;
                    case "name 2":
                        MessageBox.Show("y");
                        break;
                    default:

                        break;
                }
            }
        }

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

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