Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF double click edit label

Tags:

c#

wpf

widget

I have a label displaying some content. When a user double clicks the label, it should enable a user to change the content.

I did some research and found that it's usually very complex to achieve this simple effect. http://ludovic.chabant.com/devblog/2010/10/05/making-wpf-controls-double-clickable/

But all I need is a label (or textbox) that can be editable when double clicked. Is there a simpler way to do this?

Thanks!

like image 421
Ovilia Avatar asked May 15 '26 22:05

Ovilia


2 Answers

I think you have to handle some events (setting up all in XAML code is not possible):

//Initially set Focusable to false
textBox1.Focusable = false;
textBox1.Cursor = Cursors.Arrow;

//FocusableChanged event handler for your textBox1
private void textBox1_FocusableChanged(object sender, 
                                       DependencyPropertyChangedEventArgs e){
  textBox1.Cursor = textBox1.Focusable ? Cursors.IBeam : Cursors.Arrow;
}
//MouseDoubleClick event handler for your textBox1
private void textBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e){
  textBox1.Focusable = true;
  textBox1.Focus();
  textBox1.CaretIndex = textBox1.Text.Length;
}
//LostFocus event handler for your textBox1
private void textBox1_LostFocus(object sender, RoutedEventArgs e){
  textBox1.Focusable = false;
}
like image 98
King King Avatar answered May 17 '26 11:05

King King


You can create a textbox like:

TextBox editLbl = new TextBox();
//add it to the controls list to display it

and set all properties of the label to the textbox like location, size etc.

Set the keydown event and on pressing enter, hide the textbox and set the value to the label.

You can also set background color theme same as your form window has to look like you are editing the label.

like image 22
Shaharyar Avatar answered May 17 '26 12:05

Shaharyar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!