有这么一个需求,界面上有很多按钮,当鼠标放到上面3秒时,就触发一个事件,事件中需要携带当前时间,鼠标位置,按钮名称,上一个按钮的名称等等信息,很简单,每个按钮绑定一个Mouseenter事件,启动计时器,在MouseLeave事件中停止计时器,当计时时间到3秒时,调用目标方法即可。但是今天出于学习目的,我不准备这么做,我准备做一个自定义的路由事件,使用时,只需要添加Hander即可。
but…演示代码就搞的简单点,不写那么多计时逻辑了,简单点:如下图,点击按钮时,就触发一个自定义事件,将Name放到上方的TextBlock
下面看代码吧:
新建一个控件类:
using System;
using System.Windows;
using System.Windows.Controls;
namespace WxDemo
{
public class CustomEventArgs : RoutedEventArgs
{
public string Info { get; set; }
public CustomEventArgs(RoutedEvent routedEvent, object source)
: base(routedEvent, source)
{
Info = (source as CustomButton)?.Name;
}
}
public class CustomButton:Button
{
public static readonly RoutedEvent CustomEvent = EventManager.RegisterRoutedEvent("Custom", RoutingStrategy.Bubble, typeof(EventHandler<CustomEventArgs>), typeof(CustomButton));
public event RoutedEventHandler DetailReport
{
add { this.AddHandler(CustomEvent, value); }
remove { this.RemoveHandler(CustomEvent, value); }
}
protected override void OnClick()
{
base.OnClick();
RaiseEvent(new CustomEventArgs(CustomEvent, this));
}
}
}
上面定义了CustomButton继承自Button,注册了一个CustomEvent路由事件,在点击按钮 时,触发 该事件.
新建一个窗口:
<Window x:Class="WxDemo.CustomEventDemo"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WxDemo"
mc:Ignorable="d"
Background="LightBlue"
Title="CustomEventDemo" Height="450" Width="800">
<Grid>
<TextBlock x:Name="text" HorizontalAlignment="Center" VerticalAlignment="Top"/>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<local:CustomButton x:Name="Button1" Content="Button1" Padding="10" Margin="10" FontSize="18"/>
<local:CustomButton x:Name="Button2" Content="Button2" Padding="10" Margin="10" FontSize="18"/>
</StackPanel>
</Grid>
</Window>
窗口包含两个按钮和一个textblock
该窗体后台代码:
using System.Windows;
namespace WxDemo
{
public partial class CustomEventDemo : Window
{
public CustomEventDemo()
{
InitializeComponent();
Button1.AddHandler(CustomButton.CustomEvent, new RoutedEventHandler(EventHander));
Button2.AddHandler(CustomButton.CustomEvent, new RoutedEventHandler(EventHander));
}
private void EventHander(object sender,RoutedEventArgs args)
{
text.Text = (args as CustomEventArgs)?.Info;
}
}
}
添加了两个按钮的自定义事件。并在事件中设置TextBlock的值。
这样一个定义路由事件的流程就完了,逻辑相关的,就靠自己了。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容