Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select ListBox item only on Click or Enter key in Silverlight

When I populate a ListBox with RIA Services, an item is automatically selected. This triggers the SelectionChanged event. If I move the selection up or down with the arrow keys, the event also gets triggered.

I don't want this. I want the user to press enter or click the item for it to be selected. How do I accomplish this?

like image 314
Shawn Mclean Avatar asked Jun 17 '11 15:06

Shawn Mclean


1 Answers

You could handle the MouseLeftButtonDown and KeyDown events for the ListBox. For the KeyDown event, you'll need to check the EventArgs to determine whether the Enter key was pressed (as opposed to any other key).

These events can fire even when an item is not selected (e.g., if the user clicks inside the ListBox but not over an actual item), so within your event handlers you should check for this.

Your event handlers might look something like this:

public void MyListBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
   ItemSelected();
}

public void MyListBox_KeyDown(object sender, KeyEventArgs e)
{
   if ((e.Key & Key.Enter) == Key.Enter)
   {
      ItemSelected();
   }
}

public void ItemSelected()
{
   if (MyListBox.SelectedItem != null)
   { 
      // Handle item selection here
   } 
}

These are off the top of my head, so you may need to tweak these slightly to get them to work exactly right. Hopefully you see the general idea though.


Another way to do it would be to simply remove the SelectionChanged event handler when populating the ListBox with items (use the "-=" syntax), then re-attach it once this operation is complete.

I'd recommend doing it this way (since you're concerned about the event firing when the list is populated). It wouldn't stop the users from selecting items using the Up and Down arrow keys, but unless you have a really good reason for doing so you're making things unnecessary inconvenient (users don't want to be arbitrarily restricted from doing things that ought to work).

like image 100
Donut Avatar answered Nov 11 '22 01:11

Donut