且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 WPF 中为用户控件创建用户定义(新)事件?一个小例子

更新时间:2023-11-30 15:39:46

关于如何从主窗口可以注册的 UserControl 公开事件的简要示例:

A brief example on how to expose an event from the UserControl that the main window can register:

在您的用户控件中:

1.添加以下声明:

public event EventHandler UserControlClicked;

2.在您的 UserControl_Clicked 事件中引发事件,例如这个:

2 . In your UserControl_Clicked event raise the event like this:

 private void UserControl_MouseDown(object sender, MouseButtonEventArgs e)
 {
        if (UserControlClicked != null)
        {
            UserControlClicked(this, EventArgs.Empty);
        }
  }

在主窗口中:

您的用户控件现在将有一个 UserControlClicked 事件,您可以注册到该事件:

Your usercontrol will now have a UserControlClicked event which you can register to:

<local:UserControl1 x:Name="UC" UserControlClicked="UC_OnUserControlClicked" />