public class ReportTimeEventArgs:RoutedEventArgs
{
public ReportTimeEventArgs(RoutedEvent routedEvent, object source) : base(routedEvent, source) { }
public DateTime ClickTime { get; set; }
}
public class TimeButton : Button
{
//声明和注册路由事件
public static readonly RoutedEvent ReportTimeEvent = EventManager.RegisterRoutedEvent("ReportTime", RoutingStrategy.Tunnel,typeof(EventHandler<ReportTimeEventArgs>),typeof(TimeButton));
//CLR事件包装器
public event RoutedEventHandler ReportTime
{
add { this.AddHandler(ReportTimeEvent, value); }
remove { this.RemoveHandler(ReportTimeEvent, value); }
}
//激发路由事件,借用Click事件的激活方法
protected override void OnClick()
{
base.OnClick();//保证Button的原有功可以正常使用、Click事件能被激发。
ReportTimeEventArgs args = new ReportTimeEventArgs(ReportTimeEvent, this);
args.ClickTime = DateTime.Now;
this.RaiseEvent(args);
}
}
xml---------------- 代码--------------------------------
<Window x:Class="WpfApplication1.Window25"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local ="clr-namespace:WpfApplication1.Model"
Title="Window25" Height="300" Width="300" x:Name="Window225" local:TimeButton.ReportTime="ReportTimeHandle">
<Grid x:Name="gd_1" Margin="10" Background="AliceBlue" local:TimeButton.ReportTime="ReportTimeHandle">
<Grid x:Name="gd_2" Margin="10" Background="AntiqueWhite" local:TimeButton.ReportTime="ReportTimeHandle">
<Grid x:Name="gd_3" Margin="10" Background="Aqua" local:TimeButton.ReportTime="ReportTimeHandle">
<StackPanel Margin="10" Background="Aquamarine" x:Name="sp_1" local:TimeButton.ReportTime="ReportTimeHandle">
<ListBox x:Name="lb_view" MinHeight="30" MaxHeight="150"></ListBox>
<local:TimeButton x:Name="tb_main" local:TimeButton.ReportTime="ReportTimeHandle" Content="Test" Width="50"></local:TimeButton>
</StackPanel>
</Grid>
</Grid>
</Grid>
</Window>