简体   繁体   English

需要捕获按下ListBoxItem的事件

[英]Need to catch event of the pressing ListBoxItem

In my WPF program I have a ListBox component and some ListBoxItems in it. 在我的WPF程序中,我有一个ListBox组件和一些ListBoxItems When I press on the list's elements, I need to catch the event, but my code doesn't work: 当我按下列表的元素时,我需要捕获事件,但我的代码不起作用:

    private void mailsListBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        MessageBox.Show("-------------"); // even this doesn't work
        switch (mailsListBox.SelectedIndex)
        {
            // this doesn't work too...
            case 0: MessageBox.Show("00"); break;
            case 1: MessageBox.Show("11"); break;
            case 2: MessageBox.Show("22"); break;
            default: break;
        }
    }

Should I catch event MouseLeftButtonDown ? 我应该捕获事件MouseLeftButtonDown吗?

       <TabItem Header="Mail" BorderThickness="0" Margin="0" IsSelected="True">
            <Grid Background="#FFE5E5E5" Margin="0,5,0,0">
                <ListBox x:Name="mailsListBox" MouseLeftButtonDown="mailsListBox_MouseLeftButtonDown" >
                    <ListBoxItem Content="..." Margin="0,0,0,1"/>
                    <ListBoxItem Content="..." Margin="0,0,0,1" />
                </ListBox>
            </Grid>
        </TabItem>

我认为如果你处理SelectionChanged事件会更好。

As tagaPdyk said you should actually catch the SelectionChanged OR the SelectedIndexChanged event event like such: 正如tagaPdyk所说,你应该实际捕获SelectionChangedSelectedIndexChanged事件事件,如下所示:

private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
        //maybe check if there actually is a selection
        if(listBox1.SelectedItems[0] != null)
        {
                var item = listBox1.SelectedItems[0];
                //do something with your item
        }
}

You can actually get ALL selected items in a listbox(returns an array ), or just get the 1st item by using listBox1.SelectedItems[0] . 您实际上可以在列表框中获取所有选定的项目(返回一个array ),或者只使用listBox1.SelectedItems[0]获取第一个项目。 In your control's properties you can define if you want multiselect or not. 在控件的properties您可以定义是否需要多选。

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

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