這篇簡單的說明一下在WPF中事件傳遞的部分,下面是測試的程式碼
這篇簡單的說明一下在WPF中事件傳遞的部分,下面是測試的程式碼
Class Window1 Dim sp As StackPanel Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded sp = New StackPanel Me.Content = sp Dim tb As New TextBlock tb.Text = "I am a TextBlock" sp.Children.Add(tb) Dim btn As New Button btn.Content = "Button" sp.Children.Add(btn) Dim txt As New TextBox txt.Text = "Test words" sp.Children.Add(txt) AddHandler Me.MouseDown, AddressOf El_OnMouseDown End Sub Protected Sub El_OnMouseDown(ByVal sender As Object, ByVal e As MouseButtonEventArgs) If e.ChangedButton = MouseButton.Right Then Me.Title = "Source:" & e.Source.ToString & " OriginalSource:" & e.OriginalSource.ToString If CType(e.Source, FrameworkElement).Margin = New Thickness(5) Then CType(e.Source, FrameworkElement).Margin = New Thickness(1) Else CType(e.Source, FrameworkElement).Margin = New Thickness(5) End If End If End Sub End Class
執行程式碼之後,在Button或是TextBlock的上面按下滑鼠右鍵,你會發現該元素的邊界變大了
,要留意的是,我們只有在"Me"(Window)的MouseDown掛載事件喔,以往如果是Windows
Form,點在Button上面,那麼Form就收不到事件了。
事件傳遞會牽涉到"邏輯樹"以及"視覺樹",這部分等之後有機會我們再來說明,有興趣的可以先到書店翻翻書