【WPF】控制元件的ContextMenu屬性設定
阿新 • • 發佈:2019-01-13
效果
功能
1.使用Image、Label、Button等控制元件,實現單擊出現選單的樣式
2.將右鍵單擊顯示選單改為左鍵單擊顯示
程式碼
設計介面
<Image x:Name="ImMenu" Initialized="ImMenu_Initialized" Source="image/1.jpg" MouseEnter="ImMenu_MouseEnter" Margin="0,5,314,0.4"> <Image.ContextMenu> <ContextMenu Name="SetMenu"> <MenuItem Name="About" Header="關於" Click="About_Click"/> <MenuItem Name="Record" Header="番茄記錄" Click="Record_Click" /> <MenuItem Name="Defined" Header="自定義" Click="Defined_Click" /> </ContextMenu> </Image.ContextMenu> </Image>
後臺
/// <summary> /// 窗體載入 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Window_Loaded(object sender,RoutedEventArgs e) { //實現選單欄左鍵單擊顯示 ImMenu.MouseDown += (obj, args) => { SetMenu.IsOpen = true; }; } /// <summary> /// 選單事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ImMenu_Initialized(object sender, EventArgs e) { this.ImMenu.ContextMenu = null;//限制按鈕的右鍵單擊顯示選單功能 }