在Windows 8中的控件中有TextBox等输入控件的ContextMenuOpening事件和Button等非输入控件的RightTapped事件。
本文中将讲述者两个事件的用法。这两个事件的
PopupMenu是右键弹出菜单的具体类。
首先我们看具体菜单类的实例化和获取项目代码
/// <summary> /// 设置右键点击点击具体处理细节 /// </summary> /// <param name="sender"></param> public async void SetRightClick(object sender) { //增加菜单 PopupMenu 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("Full Screen", null, 3)); menu.Commands.Add(new UICommand("Snap Screen", null, 4)); //获取选择的菜单项 var cmd = await menu.ShowForSelectionAsync(GetRectPosition((FrameworkElement)sender)); if (cmd != null) { switch ((int)cmd.Id) { case 0: tbText.Text = "选择了(" + cmd.Label + ") ,其ID为" + cmd.Id; break; case 1: tbText.Text = "选择了(" + cmd.Label + "),其ID为" + cmd.Id; break; case 2: tbText.Text = "选择了(" + cmd.Label + ") ,其ID为" + cmd.Id; break; case 3: tbText.Text = "选择了(" + cmd.Label + ") ,其ID为" + cmd.Id; break; case 4: tbText.Text = "选择了(" + cmd.Label + ") ,其ID为" + cmd.Id; break; } } else { tbText.Text = "上下文菜单"; } } //获取菜单位置 Rect GetRectPosition(FrameworkElement element) { GeneralTransform btnform = element.TransformToVisual(null); Point point = btnform.TransformPoint(new Point()); return new Rect(point, new Size(element.ActualWidth, element.ActualHeight)); }
然后我们看看注册两个控件的右键处理事件如下:
/// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); //上下文菜单 this.tbName.ContextMenuOpening += tbName_ContextMenuOpening; //右键菜单 this.gdMenu.RightTapped += gdMenu_RightTapped; } /// <summary> /// 右键菜单事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void gdMenu_RightTapped(object sender, RightTappedRoutedEventArgs e) { SetRightClick(sender); } /// <summary> /// 上下文菜单 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void tbName_ContextMenuOpening(object sender, ContextMenuEventArgs e) { SetRightClick(sender); } /// <summary> /// 事件卸载 /// </summary> /// <param name="e"></param> protected override void OnNavigatedFrom(NavigationEventArgs e) { base.OnNavigatedFrom(e); //上下文菜单 this.tbName.ContextMenuOpening -= tbName_ContextMenuOpening; //右键菜单 this.gdMenu.RightTapped -= gdMenu_RightTapped; }
再次看看前台Xaml代码如下:
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}" Name="gdMenu"> <TextBox HorizontalAlignment="Left" Margin="141,164,0,0" TextWrapping="Wrap" Name="tbName" Text="" VerticalAlignment="Top" Height="157" Width="540"/> <TextBox HorizontalAlignment="Left" Margin="210,353,0,0" TextWrapping="Wrap" Name="tbText" Text="" VerticalAlignment="Top" Width="290"/> </Grid>
如需源码请点击 Win8Menu.rar 下载,下面是效果图.