Domanda

I am trying to understand how RoutedEvents work. Well - I walked through some tutorials and understood why RoutedEvents are useful and how they work. But there is one thing, that I don't get:

Let's say I wrote a class (e.g. "MyClass") , which has a RoutedEvent property, sth. like this:

public class MyClass 
{
public static readonly RoutedEvent myEvent;
...
}

Well - just giving a property is not enough - so I have to register the RoutedEvent with the help of EventManager:

...
myEvent = EventManager.RegisterRoutedEvent("MyEvent", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyClass));
...

Okay - now the WPF event system knows about THIS event. If I do it that way, each class I write will have it's own RoutedEvent. But that makes no sense to me.

What I want, is that other classes listen to the same event - without being a type of MyClass.

For example: I have a stackpanel and within the stackpanel is a button. Clicking the stackpanel will raise the onClick event. Clicking the button will raise the onClick event of the button - and then the onClick event on the stackpanel. But how?

Sorry - it's hard for me to describe the problem - I am just too confused :)

Thx a lot. CodeCannibal

È stato utile?

Soluzione

What I want, is that other classes listen to the same event - without being a type of MyClass.

You expect the right from this and this is what it delivers. I mean by registering a RoutedEvent you are not strongly binding it to the type; instead you are bridging it using the string "MyEvent" EventManager.RegisterRoutedEvent("MyEvent", ...

RoutedEvent traverse through the logical tree and stops traversing when handled (exceptions are there).

So, StackPanel need not to be derived from MyClass. You just need to register the RoutedEvent at StackPanel by specifying the action/handler. Whenever the RoutedEvent traverse through StackPanel it will call the corresponding action.

For example:

UserControl1.cs

//Routed Event
public static readonly RoutedEvent ThisIsEvent = EventManager.RegisterRoutedEvent("ThisIs", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(UserControl1));

// .NET wrapper
public event RoutedEventHandler ThisIs
{
    add { AddHandler(ThisIsEvent, value); }
    remove { RemoveHandler(ThisIsEvent, value); }
}

//local handler where RaiseEvent is called
private void button1_Click(object sender, RoutedEventArgs e)
{
    RaiseEvent(new RoutedEventArgs(ThisIsEvent));
}

And below is how you subscribe to that event in you XAML. You can also do this in your code file...

<StackPanel Orientation="Vertical" **local:UserControl1.ThisIs="StackPanel_ThisIs"** >
    <local:UserControl1></local:UserControl1>
</StackPanel>

I hope this clear your doubts.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top