raising a custom routed event
Hi there,
well, it appears there are many things I don't understand! Can you imagine that? At any rate I am creating a custom routed event (for practice not a work thing or anything) and don't really seem to grasp how to cause the thing to fire or get raised. Let me show you the code and explain what I mean.
Here is the XAML
Code:
<Window x:Class="RoutedEventTestTwo.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:RoutedEventTestTwo"
Title="Window1" Height="300" Width="300">
<Grid>
<local:MyButton Width="200" Height="30" x:Name="myButton" Content="My Button" />
</Grid>
</Window>
Now - Here is the code for the window
Code:
namespace RoutedEventTestTwo
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
//myButton.MyClick += new RoutedEventHandler(myButton_MyClick);
}
private void myButton_MyClick(object sender, RoutedEventArgs e)
{
}
}
}
And here is the code for my "MyButton" class
Code:
namespace RoutedEventTestTwo
{
public class MyButton: Button
{
public static readonly RoutedEvent myClickEvent;
static MyButton()
{
myClickEvent = EventManager.RegisterRoutedEvent("MyClick", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyButton));
}
public event RoutedEventHandler MyClick
{
add { AddHandler(myClickEvent, value); }
remove { RemoveHandler(myClickEvent, value); }
}
protected override void OnClick()
{
RaiseMyClickEvnet();
}
void RaiseMyClickEvnet()
{
RoutedEventArgs routedEventArgs = new RoutedEventArgs(MyButton.myClickEvent);
RaiseEvent(routedEventArgs);
}
}
}
The only way I can raise the event is to use the onclick method - I am trying to figure out a way around that? What if I didn't have an onlick? How would I capture and raise the event?
I keep seeing these blog posts that show you how to create the routed event using EventManager.RegisterRoutedEvent, and they tell you about creating the handler and called AddHanddler() and RemoveHandler() - that is the straight forward part (at least where I am concerned) they always seem to leave out just how to raise the event, even where they talk about it - they seem to show you the few lines of code where they create a new RoutedEventArgs but mysteriously always leave it out of context.
You can see that I tried
Code:
myButton.MyClick += new RoutedEventHandler(myButton_MyClick);
but of course that didn't work cause what is listening for it?
OK - As you can see - I am clearly missing something here... Anyone got any poiters? That would be great.
Thanks!
Re: raising a custom routed event
Is there no one that has anything to comment on this? Am I missing something so obvious?
Thanks