WPF學習日誌 ~ ContextMenu ~
在上一篇有簡單說明一下Run的用法,這篇利用Run的範例,稍微加一點東西配合快顯功能表的介面來設定字體的樣式,執行畫面如下圖
下面是測試的程式碼
下面是測試的程式碼
Class Window1
Dim sp As StackPanel
Dim txtBlock As TextBlock
Dim tmpR As Run
Dim cMenu As ContextMenu
Dim itemB As New MenuItem
Dim itemI As New MenuItem
Private Sub Window1_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
''快顯功能表初始化
cMenu = New ContextMenu
itemB = New MenuItem
itemB.Header = "Bold"
cMenu.Items.Add(itemB)
itemI = New MenuItem
itemI.Header = "Italic"
cMenu.Items.Add(itemI)
''功能表事件掛載
cMenu.AddHandler(MenuItem.ClickEvent, New RoutedEventHandler(AddressOf MenuItem_Click))
sp = New StackPanel
Me.Content = sp
txtBlock = New TextBlock
txtBlock.Height = 300
txtBlock.Width = 300
txtBlock.HorizontalAlignment = Windows.HorizontalAlignment.Center
txtBlock.Background = Brushes.AliceBlue
txtBlock.FontSize = 32
sp.Children.Add(txtBlock)
Dim strArr() As String = {"T", "H", "I", "S", " ", "A", " ", "B", "O", "O", "K"}
For Each s As String In strArr
Dim runTmp As New Run(s)
runTmp.TextDecorations = New TextDecorationCollection
txtBlock.Inlines.Add(runTmp)
txtBlock.Inlines.Add(" ")
''滑鼠進入跟離開的事件掛載
AddHandler runTmp.MouseEnter, AddressOf Run_OnMouseEnter
AddHandler runTmp.MouseLeave, AddressOf Run_OnMouseLeave
Next
End Sub
''改變字體相關設定
Protected Sub MenuItem_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
Dim tmpItem As MenuItem
tmpItem = CType(e.Source, MenuItem)
If tmpItem Is itemB Then
If tmpItem.IsChecked Then
tmpR.FontWeight = FontWeights.Normal
Else
tmpR.FontWeight = FontWeights.Bold
End If
Else
If tmpItem.IsChecked Then
tmpR.FontStyle = FontStyles.Normal
Else
tmpR.FontStyle = FontStyles.Italic
End If
End If
End Sub
''複寫滑鼠右鍵的動作
''把字體的目前設定讀出來反映到功能表上面
Protected Overrides Sub OnMouseRightButtonUp(ByVal e As System.Windows.Input.MouseButtonEventArgs)
MyBase.OnMouseRightButtonUp(e)
If e.Source.GetType Is GetType(Run) Then
tmpR = CType(e.Source, Run)
End If
If tmpR IsNot Nothing Then
If tmpR.FontWeight = FontWeights.Bold Then
itemB.IsChecked = True
Else
itemB.IsChecked = False
End If
If tmpR.FontStyle = FontStyles.Italic Then
itemI.IsChecked = True
Else
itemI.IsChecked = False
End If
cMenu.IsOpen = True
e.Handled = True
End If
End Sub
Protected Sub Run_OnMouseEnter(ByVal sender As Object, ByVal e As MouseEventArgs)
CType(e.Source, Run).FontSize = 48
CType(e.Source, Run).Foreground = Brushes.DeepPink
End Sub
Protected Sub Run_OnMouseLeave(ByVal sender As Object, ByVal e As MouseEventArgs)
CType(e.Source, Run).FontSize = 32
CType(e.Source, Run).Foreground = Me.Foreground
End Sub
End Class
留言