简体   繁体   中英

Need to catch event of the pressing ListBoxItem

In my WPF program I have a ListBox component and some ListBoxItems in it. 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 ?

       <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:

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] . In your control's properties you can define if you want multiselect or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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