基于此人写的代码,修改优化后支持批量给所有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修改:添加了剪切和粘贴动作对绑定数据源的更新。 总结
以上是内存溢出为你收集整理的silverlight中添加给TextBox批量添加右键菜单全部内容,希望文章能够帮你解决silverlight中添加给TextBox批量添加右键菜单所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)