之前wpf项目用到listbox右键编辑的功能,想到当时找资料不好找,特地将自己的结果拿出来与大家分享,探讨。
首先添加一个listbox。
<ListBox x:Name="List_lianxiren" MouseDown="List_lianxiren_MouseDown" SelectionMode="Extended" Margin="15,0" />后台代码:
TextBox txtNode = new TextBox();
ListBoxItem selectNode = null;string olddata;
//绑定数据到listboxitem;其中array不仅仅局限于数组,此处用数组举例而已;
public void BindingData(){ ListBoxItem tvi; MenuItem menuitem; ContextMenu contextmenu; for (int i = 0; i < Array.Length; i++) { tvi = new ListBoxItem();tvi.Content = Array[i].Owner;
tvi.Name = "_" + Array[i].id.ToString();contextmenu = new System.Windows.Controls.ContextMenu();
menuitem = new MenuItem(); menuitem.Header = "编辑"; menuitem.Click += new RoutedEventHandler(menuitem_Click); contextmenu.Items.Add(menuitem); contextmenu.Width = 130; tvi.ContextMenu = contextmenu; tvi.GotFocus += new RoutedEventHandler(tvi_GotFocus); List_lianxiren.Items.Add(tvi); }}
//编辑框失去焦点方式一
private void List_lianxiren_MouseDown(object sender, MouseButtonEventArgs e){ EditNameSaveToServer(); }//点击编辑按钮,变为编辑框
void menuitem_Click(object sender, RoutedEventArgs e)
{ selectNode = List_lianxiren.SelectedItem as ListBoxItem;txtNode = new TextBox();
if (!(selectNode.Content is TextBox)) { olddata= selectNode.Content.ToString(); txtNode.Text = selectNode.Content.ToString(); txtNode.MaxLength = 20; txtNode.Focus(); selectNode.Content = txtNode; }}//编辑框失去焦点方式二
void tvi_GotFocus(object sender, RoutedEventArgs e)
{ if (selectNode == null) { selectNode = sender as ListBoxItem; txtNode = new TextBox(); txtNode.Text = selectNode.Content.ToString(); olddata= selectNode.Content.ToString(); } EditNameSaveToServer();}//编辑框失去焦点后的处理事件,将数据保存到服务器什么的处理。
private void EditNameSaveToServer(){ if (!string.IsNullOrWhiteSpace(txtNode.Text)) { selectNode.Content = txtNode.Text; } else { selectNode.Content = olddata; }}
个人小站欢迎来踩: |