WPF學習日誌 ~ Menu ~
下面這篇我們用簡單的程式碼來測試一下Menu的功能,先來看看測試的程式碼
''資料繫結
LV2_Menu(0).Header = "EnableTextBlock"
LV2_Menu(0).SetBinding(MenuItem.IsCheckedProperty, "IsEnabled")
LV2_Menu(0).DataContext = txtBody
我把"Meun4"的第一個項目名稱改為"EnableTextBlock"(其實應該取做TextBox才對),然後將Checked的屬性跟IsEnable屬性"勾"在一起,這樣在Checked屬性變更時也會變更TextBox的IsEnable屬性,ataContext屬性是設定跟誰"掛勾",這部分要注意一下,可別勾錯人了~
Imports System.Windows其中我們看一下"資料繫結"的部分
Imports System.IO
Imports System.Reflection
Class Window1
Dim dp As DockPanel
Dim MotherMenu As Menu
Dim LV1_Menu(4) As MenuItem
Dim LV2_Menu(4) As MenuItem
Dim txtBody As TextBox
Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
''初始化Content的容器
dp = New DockPanel
Me.Content = dp
''實體化Menu
MotherMenu = New Menu
For i As Integer = 0 To 4
''加入第一層目錄
LV1_Menu(i) = New MenuItem
''設定Menu文字
LV1_Menu(i).Header = "Menu._" & i
MotherMenu.Items.Add(LV1_Menu(i))
For j As Integer = 0 To 4
''加入第二層目錄
LV2_Menu(j) = New MenuItem
LV2_Menu(j).Header = "Menu." & i & "-" & j
LV1_Menu(i).Items.Add(LV2_Menu(j))
If j - i = 0 Then
''加入傳說中的分格線
LV1_Menu(j).Items.Add(New Separator)
End If
''事件掛載
AddHandler LV2_Menu(j).Click, AddressOf MenuItem_Click
Next
Next
''設定TextBox相關屬性
txtBody = New TextBox
''設定可以換行
txtBody.AcceptsReturn = True
''設定卷軸自動顯示
txtBody.VerticalScrollBarVisibility = ScrollBarVisibility.Auto
txtBody.Text = "I am a TextBox"
txtBody.Background = Brushes.AliceBlue
''資料繫結
LV2_Menu(0).Header = "EnableTextBlock"
LV2_Menu(0).SetBinding(MenuItem.IsCheckedProperty, "IsEnabled")
LV2_Menu(0).DataContext = txtBody
''設定Menu Dock在頂端
DockPanel.SetDock(MotherMenu, Dock.Top)
dp.Children.Add(MotherMenu)
dp.Children.Add(txtBody)
''設定Windows不能改變大小
Me.ResizeMode = Windows.ResizeMode.CanMinimize
End Sub
Protected Sub MenuItem_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
CType(sender, MenuItem).IsChecked = Not CType(sender, MenuItem).IsChecked
End Sub
End Class
''資料繫結
LV2_Menu(0).Header = "EnableTextBlock"
LV2_Menu(0).SetBinding(MenuItem.IsCheckedProperty, "IsEnabled")
LV2_Menu(0).DataContext = txtBody
我把"Meun4"的第一個項目名稱改為"EnableTextBlock"(其實應該取做TextBox才對),然後將Checked的屬性跟IsEnable屬性"勾"在一起,這樣在Checked屬性變更時也會變更TextBox的IsEnable屬性,ataContext屬性是設定跟誰"掛勾",這部分要注意一下,可別勾錯人了~
留言