首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

Windows 8 開發入門(十六):右鍵選單(ContextMenu 與 RightTapped)實作指南

     編輯:關於C#

Windows 8 控制項提供兩種右鍵互動事件:

  • ContextMenuOpening:適用於 TextBox 等輸入類控制項
  • RightTapped:適用於 Button、Grid 等非輸入類控制項

兩者皆透過 PopupMenu 類別建立彈出選單。

核心邏輯:統一的選單建立與顯示方法

public async void SetRightClick(object sender) {
    var menu = new PopupMenu();
    menu.Commands.Add(new UICommand("複製 0", null, 0));
    menu.Commands.Add(new UICommand("剪貼 1", null, 1));
    menu.Commands.Add(new UICommand("貼上 2", null, 2));
    menu.Commands.Add(new UICommandSeparator());
    menu.Commands.Add(new UICommand("全螢幕", null, 3));
    menu.Commands.Add(new UICommand("快照螢幕", null, 4));

    // 於控制項位置顯示選單
    var cmd = await menu.ShowForSelectionAsync(GetRectPosition((FrameworkElement)sender));
    if (cmd != null) {
        tbText.Text = $"選擇了({cmd.Label}),其 ID 為 {cmd.Id}";
    } else {
        tbText.Text = "內容選單";
    }
}

// 計算控制項螢幕座標矩形
Rect GetRectPosition(FrameworkElement element) {
    var transform = element.TransformToVisual(null);
    var point = transform.TransformPoint(new Point());
    return new Rect(point, new Size(element.ActualWidth, element.ActualHeight));
}

事件註冊與解除(於 OnNavigatedTo/From 中)

protected override void OnNavigatedTo(NavigationEventArgs e) {
    base.OnNavigatedTo(e);
    tbName.ContextMenuOpening += tbName_ContextMenuOpening; // 輸入控制項
    gdMenu.RightTapped += gdMenu_RightTapped;               // 非輸入控制項
}

void gdMenu_RightTapped(object sender, RightTappedRoutedEventArgs e) {
    SetRightClick(sender);
}

void tbName_ContextMenuOpening(object sender, ContextMenuEventArgs e) {
    SetRightClick(sender);
}

protected override void OnNavigatedFrom(NavigationEventArgs e) {
    base.OnNavigatedFrom(e);
    tbName.ContextMenuOpening -= tbName_ContextMenuOpening;
    gdMenu.RightTapped -= gdMenu_RightTapped;
}

前端 XAML 佈局

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}" Name="gdMenu">
    <TextBox Name="tbName" Margin="141,164,0,0" Height="157" Width="540" .../>
    <TextBox Name="tbText" Margin="210,353,0,0" Width="290" .../>
</Grid>
右鍵選單執行效果
圖 1:Grid 與 TextBox 右鍵選單示範

原始碼下載:Win8Menu.rar

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved