65.9K
CodeProject 正在变化。 阅读更多。
Home

如何为用户控件创建事件

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (7投票s)

2009年10月16日

CPOL

2分钟阅读

viewsIcon

87155

downloadIcon

1911

关于为用户控件创建用户自定义事件的文章。

引言

在本文中,我将尝试解释如何为用户控件创建用户自定义事件以及如何引发它们。这不需要很多专业知识,并且可以非常容易地完成。要获取本文的完整工作副本,请下载与本文一起附加的项目。

背景

在各种情况下,我们希望为用户控件创建事件,并希望在完成某些操作时引发这些事件。

操作方法

在这个例子中,我将使用 ASPX 页面、用户控件、两个用户自定义类 Enum OperationEventArgs 执行一些数学计算(加、减、乘、除)。我相信您熟悉 ASPX 页面和用户控件这两个术语。我将解释我的两个类。Enum 只是一个包含我的控件将执行的数学运算的枚举的类,它看起来像这样

public enum Operation{ Addition = 1, Subtraction = 2, Multiplication = 3, Division = 4 };

我的第二个用户自定义类是 OperationEventArgs ,它继承自 System.EventArgs。我创建这个类来根据我的要求传递参数。该类包含一些 public 属性来保存某些值,并将被视为 OperationEventArgs 的参数。它看起来像这样

/// <summary>
/// Class that will represent Operation related event arguments
/// </summary>
public class OperationEventArgs : EventArgs
{
    private Operation _operationType;
    private decimal _operationResult;
    
    public OperationEventArgs()
    {
        
    }
    
    /// <summary>
    /// Constructor with parameters to initialize values
    /// </summary>
    /// <param name=""operationType"">Operation</param>
    /// <param name=""result"">decimal</param>
    public OperationEventArgs(Operation operationType, decimal result)
    {
        this._operationType = operationType;
        this._operationResult = result;
    }
    
    /// <summary>
    /// Property to get/set operation type
    /// </summary>
    public Operation OperationType
    {
        get
        {
            return this._operationType;
        }
        set
        {
            this._operationType = value;
        }
    }
    
    /// <summary>
    /// Property to get/set operation result
    /// </summary>
    public decimal OperationResult
    {
        get
        {
            return this._operationResult;
        }
        set
        {
            this._operationResult = value;
        }
    }
}    

当您在示例中看到它们运行时,您会更好地理解这些类的用法。此示例中的用户控件包含两个 TextBox 控件和一个 Button。以下代码为 UserControl 创建一个 public 事件。

//Delegate that will be the pointer for the event, contains two arguments 
//sender (object that raised it) and OperationEventArgs for the event arguments
public delegate void CalculationInProgress(object sender, OperationEventArgs e);
//Event name 
public event CalculationInProgress Calculating;    

在这个例子中,我在按钮点击事件上引发事件,但为了引发事件,不一定它们会在任何其他事件上被引发。您也可以在完成某些操作或根据您的需求后引发它们。

以下代码是在按钮的点击事件上编写的

protected void btnPerformOperation_Click(object sender, EventArgs e)
{
    //In the following lines which will perform the mathematical operations
    //you will notice that a new object of OperationEventArgs is created 
    //and the values are passed to its constructor
    
    //performs the addition operation and raise the event
    this.Calculating(this, new OperationEventArgs
    	(Operation.Addition, Convert.ToDecimal(this.txtValue1.Text) 
    	+ Convert.ToDecimal(this.txtValue2.Text)));
    //performs the subtraction operation and raise the event
    this.Calculating(this, new OperationEventArgs
    	(Operation.Subtraction, Convert.ToDecimal(this.txtValue1.Text) 
    	- Convert.ToDecimal(this.txtValue2.Text)));
    //performs the multiplication operation and raise the event
    this.Calculating(this, new OperationEventArgs
    	(Operation.Multiplicaiton, Convert.ToDecimal(this.txtValue1.Text) 
    	* Convert.ToDecimal(this.txtValue2.Text)));
    //performs the division operation and raise the event
    this.Calculating(this, new OperationEventArgs
    	(Operation.Division, Convert.ToDecimal(this.txtValue1.Text) / 
    	Convert.ToDecimal(this.txtValue2.Text)));
}    

这就是在用户控件中需要做的全部内容。

您需要在 ASPX 文件中放置的代码如下所示

<%@ Page Language="C#" 
	AutoEventWireup="true"  CodeFile="Default.aspx.cs" 
	Inherits="_Default" %>
<%@ Register Src="~/ctrlCalculator.ascx" TagPrefix="
	Calculator" TagName="Calculation" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 
	Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
    <body>
        <form id="form1" runat="server">
            <div>
                <%-- user defined control that will perform the mathematical 
		operation notice that the event which we created can be seen here --%>
                <Calculator:Calculation ID="ctrlCalculartor" runat="server" 
		OnCalculating="ctrlCalculator_Calculating"></Calculator:Calculation>
            </div>
        </form>
    </body>
</html>    

在以下代码中,我实际上在我的 aspx.cs 文件中编写了事件处理程序

/// <summary>
/// Event handler for the user defined event
/// </summary>
/// <param name=""sender"">object</param>
/// <param name=""e"">OperationEventArgs</param>
protected void ctrlCalculator_Calculating(object sender, OperationEventArgs e)
{
    //In this event handler you will notice that we can access 
    //the properties we created in the OperationEventArgs class 
    //that will provide the values assigned to them while raising event
    Response.Write(string.Format("The result of \"{0}\" 
    	operation is : {1}", e.OperationType, e.OperationResult));
}    

完成了!!!

您现在可以运行您的应用程序并为 TextBox 提供值。假设我输入了这些值 4 和 2。当点击按钮时,您将根据提供的值看到以下输出。

摘要

在本文中,我们尝试为用户控件创建一个事件,该事件将在某些数学运算上引发。我们使用了一个枚举来获取运算,并使用了一个用户自定义类 OperationEventArgs 来获取事件所需的参数。

我希望这篇文章能够轻松地传达您如何为用户控件创建用户自定义事件的想法。

历史

  • 2009 年 10 月 16 日:初始发布
© . All rights reserved.