Reputation: 3563
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>
Upvotes: 1
Views: 69
Reputation: 851
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.
Upvotes: 1