Hello everybody,
I would like to know does an event route from the root to all leaf? Lets say I have a Button and Textblock. Button is close to the top level while Textblock is somewhere in the depth of VisualTree. Now I am using EventManager.RegisterClassHandler inside
Textblock to register an handler of an event which should get called when Button raises the certain event. Will the handler get called even when button is somwhere at top level of VisualTree?
Here is code and its not working. Maybe the RoutedEvent are the wrong approach for this:
<Style TargetType="{x:Type local:MyButton1}"><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type local:MyButton1}"><Button><local:MyTextBlock1 Text="Not working yet."/></Button></ControlTemplate></Setter.Value></Setter></Style></Window.Resources><Grid><local:MyButton1 x:Name="myButton1" Width="200" Height="40" Click="MyButton_Click"/></Grid>
private void MyButton_Click(object sender, RoutedEventArgs e) { this.myButton1.RaiseDoSomething(); }
class MyButton1 : Button { public static readonly RoutedEvent PreviewDoSomethingEvent = EventManager.RegisterRoutedEvent("DoSomething", RoutingStrategy.Tunnel, typeof(RoutedEventHandler), typeof(MyButton1)); public event RoutedEventHandler PreviewDoSomething { add { AddHandler(PreviewDoSomethingEvent, value); } remove { RemoveHandler(PreviewDoSomethingEvent, value); } } public void RaiseDoSomething() { this.RaiseEvent(new RoutedEventArgs(PreviewDoSomethingEvent)); } } class MyTextBlock1 : TextBlock { static MyTextBlock1() { EventManager.RegisterClassHandler(typeof(MyTextBlock1), MyButton1.PreviewDoSomethingEvent, new RoutedEventHandler(OnDoSomething)); } public static void OnDoSomething(object sender, RoutedEventArgs e) { MyTextBlock1 txtBlock = sender as MyTextBlock1; if (txtBlock != null) { txtBlock.Text = "It worked! Yay!"; } } }
As you can see MyButton is close to the top of the VisualTree and MyTextBlock is somewhere deep down. Still I wish once I click on MyButton to also call the registered handler to the event from MyTextblock. The text should then be changed to "It worked yay".
How do I do this? How to go top down the VisualTree and notify via events? The code I just posted is not working. There must be something that I am missing.