本文共 2944 字,大约阅读时间需要 9 分钟。
Metro style App ContextMenu Summary。
Fist let us see the effect pictures。
Picture 1.
Picture 2.
Get the frameworkElement Rect。
public static Rect GetElementRect(FrameworkElement element) { GeneralTransform buttonTransform = element.TransformToVisual( null ); Point point = buttonTransform.TransformPoint( new Point()); return new Rect(point, new Size(element.ActualWidth, element.ActualHeight)); } |
Next is a image righttap event。
private async void AttachmentImage_RightTapped( object sender, RightTappedRoutedEventArgs e) { var menu = new PopupMenu(); menu.Commands.Add( new UICommand( "Open with" , (command) => { //ToDo:function })); menu.Commands.Add( new UICommand( "Save attachment" , (command) => { //ToDo:function })); var chosenCommand = await menu.ShowForSelectionAsync(GetElementRect((FrameworkElement)sender)); if (chosenCommand == null ) { // The command is null if no command was invoked. //ToDo:function } } |
2.Another sample
returns a rect for selected text
// returns a rect for selected text private Rect GetTextboxSelectionRect(TextBox textbox) { Rect rectFirst, rectLast; if (textbox.SelectionStart == textbox.Text.Length) { rectFirst = textbox.GetRectFromCharacterIndex(textbox.SelectionStart - 1, true ); } else { rectFirst = textbox.GetRectFromCharacterIndex(textbox.SelectionStart, false ); } int lastIndex = textbox.SelectionStart + textbox.SelectionLength; if (lastIndex == textbox.Text.Length) { rectLast = textbox.GetRectFromCharacterIndex(lastIndex - 1, true ); } else { rectLast = textbox.GetRectFromCharacterIndex(lastIndex, false ); } GeneralTransform buttonTransform = textbox.TransformToVisual( null ); Point point = buttonTransform.TransformPoint( new Point()); return new Rect(point.X + rectFirst.Left, point.Y + rectFirst.Top, rectLast.Right - rectFirst.Left, rectLast.Bottom - rectFirst.Top); } |
Next is a TextBox ContextMenuOpening event.
private async void ReadOnlyTextBox_ContextMenuOpening( object sender, ContextMenuEventArgs e) { e.Handled = true ; TextBox textbox = (TextBox)sender; if (textbox.SelectionLength > 0) { var menu = new PopupMenu(); menu.Commands.Add( new UICommand( "Copy" , null , 1)); menu.Commands.Add( new UICommandSeparator()); menu.Commands.Add( new UICommand( "Highlight" , null , 2)); menu.Commands.Add( new UICommand( "Look up" , null , 3)); Rect rect = GetTextboxSelectionRect(textbox); var chosenCommand = await menu.ShowForSelectionAsync(rect); if (chosenCommand != null ) { switch (( int )chosenCommand.Id) { case 1: //Next is copy function String selectedText = ((TextBox)sender).SelectedText; var dataPackage = new DataPackage(); dataPackage.SetText(selectedText); Clipboard.SetContent(dataPackage); break ; case 2: //Todo:function break ; case 3: //Todo:function break ; } } else { //Todo:function } } else { //Todo:function } } |
The source sample is from msdn.
本文转自Work Hard Work Smart博客园博客,原文链接:http://www.cnblogs.com/linlf03/archive/2012/08/01/2618865.html,如需转载请自行联系原作者