记录自定义事件到每个节点的事件
<Window x:Class="WpfDemo.SelfDefinedRoutedEvent" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="SelfDefinedRoutedEvent" Height="300" Width="300" xmlns:local="clr-namespace:WpfDemo" xmlns:sys="clr-namespace:System;assembly=mscorlib" > <Grid x:Name="grd1" local:TimeButton.ReportTime="ReportTimeHandle"> <Grid x:Name="grd2" local:TimeButton.ReportTime="ReportTimeHandle"> <Grid local:TimeButton.ReportTime="ReportTimeHandle" x:Name="grd3" HorizontalAlignment="Left" Height="249" Margin="10,10,0,0" VerticalAlignment="Top" Width="272"> <local:TimeButton x:Name="tb1" local:TimeButton.ReportTime="ReportTimeHandle" Content="Click" Margin="78,10,79,221"></local:TimeButton> <ListBox x:Name="listbox1" HorizontalAlignment="Left" Height="189" Margin="10,50,0,0" VerticalAlignment="Top" Width="248"/> </Grid> </Grid> </Grid> </Window>
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace WpfDemo { /// <summary> /// SelfDefinedRoutedEvent.xaml 的交互逻辑 /// </summary> public partial class SelfDefinedRoutedEvent : Window { public SelfDefinedRoutedEvent() { InitializeComponent(); } public void ReportTimeHandle(Object sender,ReportTimeEventArgs e) { FrameworkElement element = sender as FrameworkElement; string time = e.ClieckTime.ToString("yyyy/MM/dd hh/mm/ss"); string str = string.Format("{0}到达{1}", time, element.Name); listbox1.Items.Add(str); } } public class ReportTimeEventArgs:RoutedEventArgs { public ReportTimeEventArgs(RoutedEvent routedEvent, Object source) : base(routedEvent,source) { } public DateTime ClieckTime { get; set; } } public class TimeButton:Button { public static readonly RoutedEvent ReportTimeEvent=EventManager.RegisterRoutedEvent ("ReportTime", RoutingStrategy.Bubble, typeof(EventHandler<ReportTimeEventArgs>), typeof(TimeButton)); //CLR事件包装 public event RoutedEventHandler ReportTime { add{ this.AddHandler(ReportTimeEvent,value);} remove{ this.RemoveHandler(ReportTimeEvent,value);} } protected override void OnClick() { base.OnClick(); ReportTimeEventArgs args = new ReportTimeEventArgs(ReportTimeEvent, this); args.ClieckTime = DateTime.Now; this.RaiseEvent(args); } } }