路由事件中級案例
阿新 • • 發佈:2019-01-05
前端:
<Grid Name="grid1" local:TimeReportButton.TimeReport="TimeReportHandler"> <Grid Name="grid2" local:TimeReportButton.TimeReport="TimeReportHandler"> <StackPanel Name="stackP1" local:TimeReportButton.TimeReport="TimeReportHandler"> <ListBox Name="listBox1" local:TimeReportButton.TimeReport="TimeReportHandler"/> <local:TimeReportButton x:Name="btn1" Width="100" Height="30" Content="OK" TimeReport="TimeReportHandler"/> </StackPanel> </Grid> </Grid>
後臺:
public partial class Window2 : Window { public Window2() { InitializeComponent(); } public void TimeReportHandler(object source, ReportTimeEventArgs2 e) { if (e.OriginalSource != null) { listBox1.Items.Add((source as FrameworkElement).Name); } } } public class ReportTimeEventArgs2 : RoutedEventArgs { public DateTime ClickTime { get;set; } public ReportTimeEventArgs2(RoutedEvent routedEvent,object source) : base(routedEvent,source) { } } public class TimeReportButton : Button { public static readonly RoutedEvent TimeReportEvent = EventManager.RegisterRoutedEvent("TimeReport", RoutingStrategy.Bubble, typeof(EventHandler<ReportTimeEventArgs2>), typeof(TimeReportButton)); public event RoutedEventHandler TimeReport { add { this.AddHandler(TimeReportEvent, value); } remove { this.RemoveHandler(TimeReportEvent, value); } } public TimeReportButton() : base() { } protected override void OnClick() { base.OnClick(); ReportTimeEventArgs2 reportTimeArg = new ReportTimeEventArgs2(TimeReportEvent, this); reportTimeArg.ClickTime = DateTime.Now; this.RaiseEvent(reportTimeArg); } }