/// <summary>开始编辑控件的名称,资源在控件加载完毕后才有效</summary> public void HeaderEdit(CancelEditEventHandler EditHeaderClosing) { TextBox textBox = GetTemplateChild("PART_HeaderEdit") as TextBox; if (textBox != null) { textBox.Visibility = Visibility.Visible; textBox.Text = (string)Header; textBox.SelectAll(); textBox.Focus(); Window parentWindow = Window.GetWindow(textBox); MouseButtonEventHandler parentMouseDown = null; parentMouseDown = (sender, e) => { if (parentWindow.GetElementUnderMouse <TextBox>() != textBox) { textBox.Visibility = Visibility.Collapsed; CancelEditEventArgs cancelEditEventArgs = new CancelEditEventArgs((string)Header, textBox.Text); EditHeaderClosing?.Invoke(this, cancelEditEventArgs); if (cancelEditEventArgs.Cancel == false) { Header = cancelEditEventArgs.NewValue; } parentWindow.PreviewMouseDown -= parentMouseDown; } }; parentWindow.PreviewMouseDown += parentMouseDown; } }
/// <summary>开始编辑控件的名称,资源在控件加载完毕后才有效</summary> public void HeaderEdit(CancelEditEventHandler EditHeaderClosing) { TextBox textBox = GetTemplateChild("PART_HeaderEdit") as TextBox; if (textBox != null) { textBox.Visibility = Visibility.Visible; textBox.Text = (string)Header; textBox.SelectAll(); textBox.Focus(); Window parentWindow = Window.GetWindow(textBox); MouseButtonEventHandler parentMouseDown = null; KeyEventHandler keyDown = null; RoutedEventHandler lostFocus = null; Action CloseHeaderEdit = () =>//关闭编辑器 { textBox.Visibility = Visibility.Collapsed; CancelEditEventArgs cancelEditEventArgs = new CancelEditEventArgs((string)Header, textBox.Text); EditHeaderClosing?.Invoke(this, cancelEditEventArgs); if (cancelEditEventArgs.Cancel == false) { Header = cancelEditEventArgs.NewValue; } textBox.KeyDown -= keyDown; textBox.LostFocus -= lostFocus; parentWindow.PreviewMouseDown -= parentMouseDown; }; keyDown = (sender, e) => { if (e.Key == Key.Enter) { CloseHeaderEdit(); } }; parentMouseDown = (sender, e) => { if (parentWindow.GetElementUnderMouse <TextBox>() != textBox) { CloseHeaderEdit(); } }; lostFocus = (sender, e) => { CloseHeaderEdit(); }; textBox.KeyDown += keyDown; textBox.LostFocus += lostFocus; parentWindow.PreviewMouseDown += parentMouseDown; } }