简体   繁体   中英

Raising an event from child control to parent control

I have a class (which extends Framework Element) which contains within it a number of other Elements.

    // Click event coverage area
    private Rectangle connectorRectangle;

These shapes all have their event handlers, and when the user clicks on them its working well. Now what I want is to be able to 'handle' a right-click on my class from outside the scope of the class.

So I figured the best way to do it is to handle the event internally, and somehow bubble it to the top

private void connectorRectangle_MouseRightButtonUp(object sender, MouseButtonEventArgs e)

        MouseButtonEventArgs args = new MouseButtonEventArgs();

        //???
        e.Handled = true;
    }

The problem is that I have no idea how to raise the event. this.OnMouseRightButtonUp doesn't exist, and all the tutorials I'm finding are for raising custom events.

I'm pretty new to silverlight, so bear with me if I missed something obvious.

Try it :

public Rectangle
{    
   this.Click += new System.EventHandler(Function);  
}

private void Function(object sender, System.EventArgs e)
{
   if (((MouseEventArgs)e).Button == MouseButtons.Right)
   {
       //Your code         
   }
}

Your "exteded Framework Element class" shouldn't handel the mouse event (or if they handel them, set e.Handled to false). Then the event should bubble up automatically (without reraise the event).

EDIT

public class ExtendedFrameworkElement : Grid
{
    public ExtendedFrameworkElement()
    {
        Border b1 = new Border();
        b1.Padding = new Thickness(20);
        b1.Background = Brushes.Red;
        b1.MouseRightButtonUp += b1_MouseRightButtonUp;

        Border b2 = new Border();
        b2.Padding = new Thickness(20);
        b2.Background = Brushes.Green;
        b2.MouseRightButtonUp += b2_MouseRightButtonUp;

        b1.Child = b2;

        this.Children.Add(b1);
    }

   private void b1_MouseRightButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        //DoSomeThing
        e.Handled = false;
    }

  private void b2_MouseRightButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        //DoSomeThing
        e.Handled = false;
    }
}

Xaml:

<Window x:Class="WpfApplicationTest.MainWindow">
    <wpfApplicationTest:ExtendedFrameworkElement MouseRightButtonUp="UIElement_OnMouseRightButtonUp"/>
</Window>

Code Behind:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }


    private void UIElement_OnMouseRightButtonUp(object sender, MouseButtonEventArgs e)
    {
        //DoSomeThing
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM