其原理的就是在處理初始button元素的點擊事件方法時,同時委託方法到新建項button的點擊事件上。編程
private void MakeButton(object sender, RoutedEventArgs e) { var b2 = new Button {Content = "New Button"}; // Associate event handler to the button. You can remove the event // handler using "-=" syntax rather than "+=". b2.Click += Onb2Click; root.Children.Insert(root.Children.Count, b2); DockPanel.SetDock(b2, Dock.Top); text1.Text = "Now click the second button..."; b1.IsEnabled = false; }
界面自定義button樣式設計及自定義路由事件Tap附加方法ide
<Window.Resources> <Style TargetType="{x:Type local:MyButtonSimple}"> <Setter Property="Height" Value="20"/> <Setter Property="Width" Value="250"/> <Setter Property="HorizontalAlignment" Value="Left"/> <Setter Property="Background" Value="#808080"/> </Style> </Window.Resources> <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center" Background="LightGray"> <local:MyButtonSimple x:Name="mybtnsimple" Tap="TapHandler">Click to see Tap custom event work</local:MyButtonSimple> </StackPanel>
自定義路由事件Tap:測試
public class MyButtonSimple : Button { // Create a custom routed event by first registering a RoutedEventID // This event uses the bubbling routing strategy public static readonly RoutedEvent TapEvent = EventManager.RegisterRoutedEvent( "Tap", RoutingStrategy.Bubble, typeof (RoutedEventHandler), typeof (MyButtonSimple)); // Provide CLR accessors for the event public event RoutedEventHandler Tap { add { AddHandler(TapEvent, value); } remove { RemoveHandler(TapEvent, value); } } // This method raises the Tap event private void RaiseTapEvent() { var newEventArgs = new RoutedEventArgs(TapEvent); RaiseEvent(newEventArgs); } // For demonstration purposes we raise the event when the MyButtonSimple is clicked protected override void OnClick() { RaiseTapEvent(); } }
很簡單的使用路由參數e,其Source包含引起事件的對象spa
private void HandleClick(object sender, RoutedEventArgs e) { // You must cast the sender object as a Button element, or at least as FrameworkElement, to set Width var srcButton = e.Source as Button; srcButton.Width = 200; }
ps:OriginalSource: 在父類進行任何可能的 Source 調整以前,獲取原始報告源(由純粹命中測試肯定)。設計
<StackPanel Name="myStackPanel" HorizontalAlignment="Center" VerticalAlignment="Center" Button.Click="HandleClick"> <StackPanel.Resources> <Style TargetType="{x:Type Button}"> <Setter Property="Height" Value="20"/> <Setter Property="Width" Value="250"/> <Setter Property="HorizontalAlignment" Value="Left"/> </Style> </StackPanel.Resources> <Button Name="Button1">Item 1</Button> <Button Name="Button2">Item 2</Button> <TextBlock Name="results"/> </StackPanel>
擴展:
如何:實現接口事件(C# 編程指南)code
RoutedEventArgs 類:包含與路由事件相關的狀態信息和事件數據。對象