Search code examples
c#wpfcomboboxhighlight

WPF ComboBox get highlighted item


I'm trying to get the value of the highlighted item of the dropdown list in a ComboBox while the dropdown list is still open.

This is because I want to show a different ToolTip for all the element in the dropdown list based on the highlighted item.

I have found some information here: http://social.msdn.microsoft.com/Forums/vstudio/en-US/822f85e7-524a-4af2-b09a-c88c94971ac0/identifying-the-highlighted-item-in-a-combobox but seems to be difficult and with a lot of code behind...

I have also try to use the IsHighlighted property of ComboBoxItem on SelectionChanged... But I give the item selected and not the highlighted one.

I also try to cycling the elements in the ComboBox in the get of property that I bind (with Databinding) to the ToolTip property of ComboBoxItems, using a function like:

foreach (ComboBoxItem comboBoxItem in comboBox.Items)
{
    if (comboBoxItem.IsHighlighted == true)
    {
        //Do something          
        break;
    }
}

But I probably do something wrong... Because comboBoxItem.IsHighlighted it is always false...


Solution

  • Thanks to this resources: http://social.msdn.microsoft.com/Forums/vstudio/en-US/ce14fc29-d320-4557-abc5-81b042730c48/how-to-get-current-combobox-item-on-which-mouse-overs-in-wpf

    I found this solution:

    In the WPF:

        <ComboBox
            Name="ComboBox1">
           <ComboBox.ItemContainerStyle>
                <Style TargetType="{x:Type ComboBoxItem}">                    
                    <EventSetter Event="MouseMove" Handler="OnMouseMove" />                        
                </Style>
            </ComboBox.ItemContainerStyle>
            <ComboBoxItem
                Content="Test1"></ComboBoxItem>
            <ComboBoxItem
                Content="Test2"></ComboBoxItem>
        </ComboBox>
    

    In the code behind:

    private void OnMouseMove(object sender, MouseEventArgs e)
        {
            ComboBoxItem highlightedComboBoxItem = sender as ComboBoxItem;
            // highlightedComboBoxItem  is true
        }