Wpf works with events

I wrote my own control with some buttons and events - it works like a charm. Then I dynamically put these controls as a child of the StackPanel in another class. How could I in this class (with StackPanel ) receive events from my custom control - I have a public event in my user control - how can I handle it from the StackPanel class?

I am trying to write something like:

  public event EventHandler<ThumbnailEventArgs> ThumbnailClick { add { AddHandler(ThumbnailClickEventRouted, value); } remove { RemoveHandler(ThumbnailClickEventRouted, value); } } public static RoutedEvent ThumbnailClickEventRouted; 

To make my public ThumbnailClick routed, but it does not work.

+4
source share
2 answers

Your routed event should bubble up, so just catch it on the stack. Make sure you select RoutingStrategy.Bubble when registering a routed event.

Mainwiindow

 <StackPanel local:UserControl1.Tap="Grid_Tap" > <local:UserControl1 Width="120"></local:UserControl1> </StackPanel> 

User control

 <Grid> <Button Click="Button_Click">Tap Me</Button> </Grid> 

User Management Code for

 public partial class UserControl1 : UserControl { public UserControl1() { InitializeComponent(); } // Create a custom routed event by first registering a RoutedEventID // This event uses the bubbling routing strategy public static readonly RoutedEvent TapEvent = EventManager.RegisterRoutedEvent( "Tap", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(UserControl1)); // Provide CLR accessors for the event public event RoutedEventHandler Tap { add { AddHandler(TapEvent, value); } remove { RemoveHandler(TapEvent, value); } } // This method raises the Tap event void RaiseTapEvent() { RoutedEventArgs newEventArgs = new RoutedEventArgs(UserControl1.TapEvent); RaiseEvent(newEventArgs); } private void Button_Click(object sender, RoutedEventArgs e) { RaiseTapEvent(); } } 

Some of the code in UserControl1 is handled from Microsoft docutments ...

0
source

Edit: You need to raise an event , as well as read the review .


If your event is publicly available, you can subscribe to it from almost anywhere:

In XAML:

 <StackPanel> <local:MyControl MyEvent="MyControl_OnMyEvent"/> 

In the corresponding *.xaml.cs :

 private void MyControl_OnMyEvent(object sender, EventArgs e) { //Handler logic here } 

Change the type of arguments as necessary.

If the event is routed , you can also subscribe to it in the StackPanel :

 <StackPanel local:MyControl.MyEvent="MyControl_OnMyEvent"> 

This allows you to handle the event of all MyControl children in one place without adding a handler to each instance.

0
source

Source: https://habr.com/ru/post/1384699/


All Articles