如何在 WPF 中为用户控件创建用户定义(新)事件?一个小例子 [英] How to create user define (new) event for user control in WPF ?one small example

查看:40
本文介绍了如何在 WPF 中为用户控件创建用户定义(新)事件?一个小例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 UserControl,我在其中使用了 Canvas,并且在该 Canvas 中使用了一个矩形.我想为该用户控件(画布和矩形)创建一个单击事件,然后我想在主窗口中使用它.

I have one UserControl in which I am using a Canvas, and in that Canvas one Rectangle. I want to create a click event for that user control (Canvas and Rectangle) which I then want to use in the main window.

问题是:我想为 UserControl 创建一个新的点击事件.怎么做?请展示小例子或代码.

The question is: I want to create a new click event for the UserControl. How to do it? Kindly show little example or the code.

推荐答案

关于如何从主窗口可以注册的 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" />

这篇关于如何在 WPF 中为用户控件创建用户定义(新)事件?一个小例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆