繁体   English   中英

从子控件引发事件到父控件

[英]Raising an event from child control to parent control

我有一个类(扩展了Framework Element),该类中包含许多其他Elements。

    // Click event coverage area
    private Rectangle connectorRectangle;

这些形状都有其事件处理程序,并且当用户单击它们时,它们的效果很好。 现在,我想要的是能够从类范围之外“处理”我的类。

因此,我认为最好的方法是在内部处理事件,并以某种方式将其冒顶

private void connectorRectangle_MouseRightButtonUp(object sender, MouseButtonEventArgs e)

        MouseButtonEventArgs args = new MouseButtonEventArgs();

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

问题是我不知道该如何筹办这项活动。 this.OnMouseRightButtonUp不存在,我正在找到的所有教程都是关于引发自定义事件的。

我是Silverlight的新手,所以如果我错过了明显的事情,请多多包涵。

试试吧 :

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

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

您的“扩展的Framework Element类”不应处理鼠标事件(或者如果处理它们,请将e.Handled设置为false)。 然后事件应自动冒泡(不重新引发事件)。

编辑

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>

背后的代码:

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


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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