action和eventhandler
时间: 2023-09-02 07:09:47 浏览: 59
Action和EventHandler都是用于处理事件的类。
Action是一个委托(Delegate),它可以封装一个方法或Lambda表达式,用于在需要时执行某些操作。Action通常用于没有返回值的事件处理程序。
EventHandler是一个委托,它专门用于处理事件。它与Action非常相似,但是它需要一个Object类型的sender参数和一个EventArgs类型的e参数。EventHandler通常用于有关信息的事件处理程序。
总的来说,Action是一个通用的委托,可以用于任何需要执行操作的情况,而EventHandler是专门用于事件处理的委托。
相关问题
c# eventhandler用法
C#中的EventHandler是一种委托类型,它可以用于处理事件。当事件被触发时,与之相关联的EventHandler将被调用。以下是使用EventHandler的示例:
1. 定义一个委托EventHandler,并将方法Cancel委托给它,然后调用委托执行:
```csharp
public delegate void EventHandler(bool cancel);
public event EventHandler WindowTryClose;
// 委托方法
private void Cancel(bool cancel)
{
// 取消关闭窗口
}
// 调用委托
WindowTryClose?.Invoke(false);
```
2. 定义一个Button类,使用EventHandler处理按钮点击事件:
```csharp
public class Button
{
public EventHandler ClickEvent;
// 触发点击事件
public void ClickAction()
{
ClickEvent?.Invoke(this, new EventArgs());
}
}
// 使用Button类
Button button = new Button();
button.ClickEvent += Button_Click;
button.ClickAction();
// 处理点击事件的方法
public void Button_Click(Object sender, EventArgs args)
{
// 处理按钮点击事件
}
```
WPF 全局 eventhandler 帮助类
WPF 中可以使用全局 event handler 帮助类来简化事件处理的代码。这个帮助类可以用来注册和注销全局事件处理程序,从而避免在每个控件上都编写事件处理程序。
下面是一个简单的实现:
```csharp
public static class GlobalEventHandlers
{
public static void Register<T>(DependencyObject obj, RoutedEvent routedEvent, Action<T, RoutedEventArgs> handler)
where T : UIElement
{
T element = obj as T;
if (element != null)
{
element.AddHandler(routedEvent, new RoutedEventHandler((sender, e) => handler((T)sender, e)));
}
}
public static void Unregister<T>(DependencyObject obj, RoutedEvent routedEvent, Action<T, RoutedEventArgs> handler)
where T : UIElement
{
T element = obj as T;
if (element != null)
{
element.RemoveHandler(routedEvent, new RoutedEventHandler((sender, e) => handler((T)sender, e)));
}
}
}
```
使用这个帮助类,可以在任何一个控件上注册全局事件处理程序,例如:
```csharp
GlobalEventHandlers.Register<Button>(Application.Current.MainWindow, Button.ClickEvent, (sender, e) =>
{
// 处理 Button 点击事件
});
```
这段代码将在应用程序的主窗口上注册一个全局的 Button 点击事件处理程序。同样的,可以使用 `GlobalEventHandlers.Unregister` 方法来注销全局事件处理程序。