Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Launch code when IsMouseOver ComboBoxItem

Tags:

c#

wpf

I have a ComboBox. Without changing the template, is there a way that I can launch code when there user places their mouse over a ComboBoxItem, but before the selection actually occurs? It seems like I should be able to specify an EventTrigger or a Trigger to do this in the style of ComboBoxItem.

<ComboBox Grid.Column="1" Grid.Row="0" 
          ItemsSource="{Binding Voices}"                                
          SelectedItem="{Binding SelectedVoice, Mode=TwoWay}">
    <ComboBox.Resources>
        <Style TargetType="{x:Type ComboBoxItem}">
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    ... Launch my code from code behind... but HOW? ...
                </Trigger>
            </Style.Triggers>
        </Style>
    </ComboBox.Resources>
</ComboBox>

I'm also ok with ousing a MouseEnter, but I would rather not build a separate DataTemplate or ContentTemplate if possible.

Update. The idea behind this snippet is to Play test audio when the user hovers over a new voice, which I would have to do from the code side. Help!

like image 587
tofutim Avatar asked Jun 14 '11 15:06

tofutim


1 Answers

You can use EventSetter:

<ComboBox.Resources>
    <Style TargetType="{x:Type ComboBoxItem}">
        <EventSetter Event="PreviewMouseMove" Handler="ComboBoxItem_PreviewMouseMove" />
    </Style>
</ComboBox.Resources>

in code behind:

private void ComboBoxItem_PreviewMouseMove(object sender, MouseEventArgs e)
{
    ComboBoxItem item = sender as ComboBoxItem;
    //Now you can use this Item
}
like image 109
Navid Rahmani Avatar answered Oct 15 '22 20:10

Navid Rahmani