WPF學習日誌 ~Menu~
這篇我們用簡單的Code來測試一下Menu(功能表)的功能,下面是測試的程式碼
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屬性,DataContext屬性是設定跟誰"掛勾",這部分要注意一下,可
別勾錯人了~
下面我將程式碼全部刪掉,用XAML來作視窗介面的部分,XAML Code會長的像下面這樣
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="Window1"
Title="Window1" Height="346" Width="469">
<DockPanel Name="dp">
<Menu Name="MotherMenu" DockPanel.Dock="Top">
<MenuItem Header="Menu0">
<MenuItem Header="Menu0-0" />
<Separator />
<MenuItem Header="Menu0-1" />
<MenuItem Header="Menu0-2" />
<MenuItem Header="Menu0-3" />
</MenuItem>
<MenuItem Header="Menu1">
<MenuItem Header="Menu1-0" />
<MenuItem Header="Menu1-1" />
<Separator />
<MenuItem Header="Menu1-2" />
<MenuItem Header="Menu1-3" />
</MenuItem>
</Menu>
<TextBox Name="txtBody" VerticalScrollBarVisibility="Auto" Background="AliceBlue" AcceptsReturn="True">
I am a TextBox
</TextBox>
</DockPanel>
</Window>
這樣跟程式碼互相搭配來看,是不是比較容易了解XAML Code的撰寫方式呢 ~