Monday, September 8, 2008

Silverlight Tip 2#: How to implement a 'Hover-Selection' for the ListBox?

I'd like my control popup (see previous post) is similar to popup of combobox with hover-selection. There is no built-in ComboBox in Silverlight 2 Beta 2 and I've used ListBox control. But you can't select ListBoxItem by moving mouse on it.

Norbert Eder has written interesting post about how to implement it for the WPF ListBox. This solution has one bug - selection doesn't work when you move mouse outside DataTemplate area (outside the text of the ListBoxItem). I've resolved the problem by adding MouseMove event handler to ItemContainerStyle instead of DataTemplate.

Because MouseLeftButtonDown event doesn't fire for ListBox, I've added MouseLeftButtonDown event handler to ItemContainerStyle, too.


<Style x:Key="DropDownListBoxItemStyle" TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Grid MouseMove="Grid_MouseMove" MouseLeftButtonDown="Grid_MouseLeftButtonDown">
...

private void Grid_MouseMove(object sender, MouseEventArgs e)
{
Grid grd = sender as Grid;
this.DropDownListBox.SelectedItem = grd.DataContext;
}

No comments: