如何在WPF中为用户控件创建用户定义(new)事件?

时间:2022-09-25 02:53:46

i have a one usercontrol in which i am using one canvas and in that canvas one rectangle is there so i want to create a click event for that user control(canvas+rectangle) which i want to use in main window.. the question is I want to create a new click event for that user control.so how to do it kindly show little example or show me code of this particular on

我有一个usercontrol,其中我使用了一个canvas,在这个canvas中有一个矩形,所以我想为这个用户控件(canvas+矩形)创建一个单击事件,我想在主窗口中使用它。问题是我想为这个用户控件创建一个新的单击事件。怎么做呢?给我举个例子或者给我看看这个特殊的代码

2 个解决方案

#1


23  

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

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

In your Usercontrol

在你的用户控件

  1. Add the following decleration:

    添加以下此话:

    public event EventHandler UserControlClicked;
    
  2. In your UserControl_Clicked event raise the event like this:

    在您的usercontrol_click事件中,像这样引发事件:

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

In your MainWindow:

在你的主窗口:

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

您的UserOontrol现在将有一个usercontrolclick事件,您可以注册到:

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

#2


0  

Read about routed events also.

还可以阅读路由事件。

Routed Events Overview

路由事件概述

How to: Create a Custom Routed Event

如何:创建自定义路由事件

#1


23  

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

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

In your Usercontrol

在你的用户控件

  1. Add the following decleration:

    添加以下此话:

    public event EventHandler UserControlClicked;
    
  2. In your UserControl_Clicked event raise the event like this:

    在您的usercontrol_click事件中,像这样引发事件:

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

In your MainWindow:

在你的主窗口:

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

您的UserOontrol现在将有一个usercontrolclick事件,您可以注册到:

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

#2


0  

Read about routed events also.

还可以阅读路由事件。

Routed Events Overview

路由事件概述

How to: Create a Custom Routed Event

如何:创建自定义路由事件