基于此人写的代码,修改优化后支持批量给所有TextBox添加右键菜单,而菜单共用一个,节省资源。
public static class CreatMenuForTextBox { // 菜单 static ContextMenu menu; //TextBox static TextBox textBox; /// <summary> /// 为任意元素的内部TextBox添加右键菜单 /// </summary> public static void creatMenu(DependencyObject obj) { menu = new ContextMenu(); menu.Items.Add(getItem("剪切","../Images/1.jpg")); menu.Items.Add(getItem("复制",null)); menu.Items.Add(getItem("粘贴",null)); menu.Items.Add(new Separator()); menu.Items.Add(getItem("选择全部",null)); menu.Opened += menu_Opened; SetMenu(obj); } static void SetMenu(DependencyObject obj) { var count = VisualTreeHelper.GetChildrenCount(obj); for (int i = 0; i < count; i++) { var child = VisualTreeHelper.GetChild(obj,i); if (child is TextBox) { ((TextBox)child).MouseRightButtonDown += TextBox_MouseRightButtonDown; } else { SetMenu(child); } } } static void TextBox_MouseRightButtonDown(object sender,MouseButtonEventArgs e) { e.Handled = true; textBox = sender as TextBox; textBox.Focus(); menu.IsOpen = true; } static void menu_Opened(object sender,RoutedEventArgs e) { textBox.Focus(); } static MenuItem getItem(string header,string imagePath) { MenuItem item = new MenuItem(); item.Header = header; if (imagePath != null) { Image im = new Image(); im.source = new ImageSourceConverter().ConvertFromString(imagePath) as ImageSource; item.Icon = im; } item.Click += new RoutedEventHandler(item_Click); return item; } static void item_Click(object sender,RoutedEventArgs e) { MenuItem menuItem = (MenuItem)sender; try { execute(menuItem.Header.ToString()); } catch (Exception) { } textBox.Focus(); } static void execute(string selected) { switch (selected) { case "剪切": Clipboard.SetText(textBox.SelectedText); textBox.SelectedText = ""; textBox.GetBindingExpression(TextBox.TextProperty).UpdateSource(); break; case "复制": Clipboard.SetText(textBox.SelectedText); break; case "粘贴": textBox.SelectedText = Clipboard.GetText(); textBox.GetBindingExpression(TextBox.TextProperty).UpdateSource(); break; case "选择全部": textBox.SelectAll(); break; default: break; } } }2013-11-20修改:添加了剪切和粘贴动作对绑定数据源的更新。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。