code_junkie

Is faking a WPF mouseover possible

Nov 13th, 2011
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. _myTextBox.GotFocus += new RoutedEventHandler(TB_GotFocus);
  2.  
  3. void TB_GotFocus(object sender, RoutedEventArgs e)
  4. {
  5. ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(this.DataTemplateInstance);
  6. DataTemplate template = myContentPresenter.ContentTemplate;
  7.  
  8. Button _button= template.FindName("TemplateButton", myContentPresenter) as Button;
  9. _button.RaiseEvent(new RoutedEventArgs(Button.MouseEnterEvent));
  10.  
  11. }
  12.  
  13. private void tb_GotFocus(object sender, RoutedEventArgs e)
  14. {
  15. // ButtonChrome is the first child of button
  16. DependencyObject chrome = VisualTreeHelper.GetChild(button, 0);
  17. chrome.SetValue(Microsoft.Windows.Themes.ButtonChrome.RenderMouseOverProperty, true);
  18. }
  19.  
  20. private void tb_LostFocus(object sender, RoutedEventArgs e)
  21. {
  22. // ButtonChrome is the first child of button
  23. DependencyObject chrome = VisualTreeHelper.GetChild(button, 0);
  24. chrome.ClearValue(Microsoft.Windows.Themes.ButtonChrome.RenderMouseOverProperty);
  25. }
  26.  
  27. <Window x:Class="WpfApplication.Window1"
  28. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  29. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  30. xmlns:local="clr-namespace:WpfApplication"
  31. Title="Window1" Height="300" Width="300">
  32.  
  33. <Window.Resources>
  34. <Style TargetType="{x:Type Button}" x:Key="MouseOverStyle">
  35. <Setter Property="Background">
  36. <Setter.Value>Green</Setter.Value>
  37. </Setter>
  38. </Style>
  39. </Window.Resources>
  40.  
  41. <Grid Height="30">
  42. <Grid.ColumnDefinitions>
  43. <ColumnDefinition Width="3*"/>
  44. <ColumnDefinition Width="*"/>
  45. </Grid.ColumnDefinitions>
  46. <TextBox x:Name="MyTextBox" Grid.Column="0" Text="Some Text" Margin="2" GotFocus="TextBox_GotFocus" LostFocus="MyTextBox_LostFocus"/>
  47. <Button x:Name="MyButton" Grid.Column="1" Content="Button" Margin="2" MouseEnter="Button_MouseEnter" MouseLeave="Button_MouseLeave" />
  48. </Grid>
  49.  
  50. public partial class Window1 : Window
  51. {
  52. Style mouseOverStyle;
  53. public Window1()
  54. {
  55. InitializeComponent();
  56. mouseOverStyle = (Style)FindResource("MouseOverStyle");
  57. }
  58. private void TextBox_GotFocus(object sender, RoutedEventArgs e) { MyButton.Style = mouseOverStyle; }
  59. private void MyTextBox_LostFocus(object sender, RoutedEventArgs e) { MyButton.Style = null; }
  60. private void Button_MouseEnter(object sender, MouseEventArgs e) { ((Button)sender).Style = mouseOverStyle; }
  61. private void Button_MouseLeave(object sender, MouseEventArgs e) { ((Button)sender).Style = null; }
  62. }
Add Comment
Please, Sign In to add comment