> 文章列表 > Windows 8 开发之上下文菜单(右键属性)的应用

Windows 8 开发之上下文菜单(右键属性)的应用

在程序中,当右键单击某个对象时,会有小小的弹出菜单命令。如果你使用过Windows 8,你可能已经遇见到过上下文菜单了。经常在一些不可以选择的对象上右键单击,或者在text文本上进行操作时,会出现上下文菜单。什么时候使用上下文菜单,微软提供了非常详细的指导,下面将介绍如何实现上下文菜单。

1.确定要显示上下文菜单的位置

当我们创建弹出菜单时,首先需要确定出被点击element所在的位置,然后将位置传递给弹出菜单控件。下面的方法是确定element的位置:

复制代码

代码如下:

privateRect GetPoint(TextBox box)

{

Rect temp = box.GetRectFromCharacterIndex(box.SelectionStart, false);

GeneralTransform transform = box.TransformToVisual(null);

Point point = transform.TransformPoint(new Point());

point.X = point.X + temp.X;

point.Y = point.Y + temp.Y;

return new Rect(point, new Size(temp.Width, temp.Height));

}

2.创建上下文菜单的选项

1)为TextBox添加上下文菜单事件

复制代码

代码如下:

protected override void OnNavigatedTo(NavigationEventArgs e)

{

InputBox.ContextMenuOpening += InputBox_ContextMenuOpening;//InputBox是UI层的TextBox控件

}

2)当离开这个页面时移除上下文菜单事件

复制代码

代码如下:

protected override void OnNavigatedFrom(NavigationEventArgs e)

{

InputBox.ContextMenuOpening -= InputBox_ContextMenuOpening;

}

3)创建了一个PopupMenu菜单,并添加了一个command,然后调用ShowForSelectionAsync()方法将其显示出来。

复制代码

代码如下:

async void InputBox_ContextMenuOpening(object sender, ContextMenuEventArgs e)

{

e.Handled =true; //来取消原来的调用,然后创建自己的上下文菜单,并在适当的地方调用剪贴板(clipboard)

TextBox box = sender as TextBox;

PopupMenu menu = new PopupMenu();//创建PopupMenu菜单

menu.Commands.Add(new UICommand(\"复制\", null, 0));

menu.Commands.Add(new UICommand(\"剪切\", null, 1));

menu.Commands.Add(new UICommand(\"粘贴\", null, 2));

menu.Commands.Add(new UICommand(\"全选\", null, 3));

menu.Commands.Add(new UICommand(\"删除\", null, 4));

var cmd = await menu.ShowForSelectionAsync(GetPoint(box)); //这里的菜单位置也可以使用 new Rect(e.CursorLeft,e.CursorTop,0,0);

if (cmd != null)

{

string text;

DataPackage package;

int index=(int)cmd.Id;

switch (index)

{

case 0:

text = box.SelectedText;

package =new DataPackage();

package.SetText(text);

Clipboard.SetContent(package);

break;

case 1:

text = box.SelectedText;

box.SelectedText =\"\";

package =new DataPackage();

package.SetText(text);

Clipboard.SetContent(package);

break;

case 2:

text =awaitClipboard.GetContent().GetTextAsync();

box.SelectedText = text;

break;

case 3:

box.SelectAll();

break;

case 4:

box.SelectedText =\"\";

break;

}

}

}

3.使用另一种方法,实现上下文菜单

1)先为TextBox注册右键事件,右键事件必须使用下面的方法注册,在页面上写RightTapped事件,是不起作用的。

复制代码

代码如下:

public MainPage()

{

this.InitializeComponent();

ContentText.AddHandler(RightTappedEvent, new RightTappedEventHandler(ContentText_RightTapped),true);

}

2).ContentText_RightTapped方法

复制代码

代码如下:

private async void ContentText_RightTapped(object sender, RightTappedRoutedEventArgs e)

{

//和 InputBox_ContextMenuOpening方法一样

}

UI层代码:

注意:在上下文菜单中,最多可以添加6个command,当添加多余6个command时,会出现错误。

上下文菜单是非常好的方法:特别是为不可选的element提供交互,或者与邻近的element进行交互。

如需源代码,点击ContextMenu_jb51net.zip下载