Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is faking a WPF mouseover possible?

I have a data template with a textbox and a button with some styles on it. I would like to have the button show the mouse over state when focus is on the textbox beside it. Is this possible?

I figure it would involve something like this. I can get the textbox through use of FindVisualChild and FindName. Then I can set the GotFocus event on the textbox to do something.

_myTextBox.GotFocus += new RoutedEventHandler(TB_GotFocus);

Here in TB_GotFocus I'm stuck. I can get the button I want to show the mouse over state of, but I don't know what event to send to it. MouseEnterEvent isn't allowed.

void TB_GotFocus(object sender, RoutedEventArgs e)
  {
     ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(this.DataTemplateInstance);
     DataTemplate template = myContentPresenter.ContentTemplate;

     Button _button= template.FindName("TemplateButton", myContentPresenter) as Button;
     _button.RaiseEvent(new RoutedEventArgs(Button.MouseEnterEvent));

  } 
like image 691
Jippers Avatar asked Jan 21 '09 00:01

Jippers


1 Answers

I don't think it's possible to fake the event but you can force the button to render itself as if it had MouseOver.

private void tb_GotFocus(object sender, RoutedEventArgs e)
{
    // ButtonChrome is the first child of button
    DependencyObject chrome = VisualTreeHelper.GetChild(button, 0);
    chrome.SetValue(Microsoft.Windows.Themes.ButtonChrome.RenderMouseOverProperty, true);
}

private void tb_LostFocus(object sender, RoutedEventArgs e)
{
    // ButtonChrome is the first child of button
    DependencyObject chrome = VisualTreeHelper.GetChild(button, 0);
    chrome.ClearValue(Microsoft.Windows.Themes.ButtonChrome.RenderMouseOverProperty);
}

you need to reference PresentationFramework.Aero.dlll for this to work and then it will only work on Vista for the Aero theme.

If you want it to work for other themes you should make a custom controltemplate for each of the theme you want to support.

See http://blogs.msdn.com/llobo/archive/2006/07/12/663653.aspx for tips

like image 90
Jesper Larsen-Ledet Avatar answered Oct 12 '22 00:10

Jesper Larsen-Ledet