Richa
Richa

Reputation: 3289

One function for multiple Textbox WPF

I have 5 textboxes that gets editable on double click.

Below is method i have written for one textbox.

private void TextBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            txtFirstLctrTime.IsReadOnly = false;
            txtFirstLctrTime.Background = new SolidColorBrush(Colors.White);
            txtFirstLctrTime.Foreground = new SolidColorBrush(Colors.Black);
        }

Is there any way i can use same method for all text box instead of writing different method for all?? I am fairly new to programming

Upvotes: 1

Views: 808

Answers (4)

Ignacio Soler Garcia
Ignacio Soler Garcia

Reputation: 21855

Another option is to inherit from TextBox and implement your specific behavior on the OnDoubleClick method.

This way you can have this control on different views without repeated code.

Upvotes: 0

MajkeloDev
MajkeloDev

Reputation: 1661

Yes, there is a way. Sender is a parameter which can tell You which controll fired this event. Look at my example below:

private void TextBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
  TextBox tbWhichFiredThisEvent = sender as TextBox;
  if(tbWhichFiredThisEvent != null)
  {
    tbWhichFiredThisEvent.IsReadOnly = false;
    // ... etc.
  }
}

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222582

Attach same handler to all textboxes and use sender argument to get textbox instance which raised event:

private void  MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
     TextBox textBox = (TextBox)sender;
    textBox.IsReadOnly = false;
    textBox.Background = new SolidColorBrush(Colors.White);
    textBox.Foreground = new SolidColorBrush(Colors.Black);
}

Upvotes: 1

nvoigt
nvoigt

Reputation: 77304

You can atach this handler to all textboxes. Then you check the sender, because that's the textbox you actually clicked:

    private void TextBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        var textBox = sender as TextBox;

        textBox.IsReadOnly = false;
        textBox.Background = new SolidColorBrush(Colors.White);
        textBox.Foreground = new SolidColorBrush(Colors.Black);
    }

You should look into MVVM and data binding thought, having click-handlers and code-behind has it's limits.

Upvotes: 3

Related Questions