Buck
Buck

Reputation: 37

Want textbox to empty when data is entered

Using C# and WPF. I have a lot of textboxes that are data bound like this:

Text="{Binding ZipCode, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"

I need an event handler that will set ZipCode to "" when the user clicks or tabs into the box to enter data. The code posted works, but I need it to be used by other textboxes. Can I do that with sender? And is this the best method to empty a textbox when clicking or tabbing into the box? Thanks.

private void ClearZipCode_GotKeyboardFocus(object sender, keyboardFocusChangedEventArgs e)
{
    allSettings.ZipCode = "";
}

Upvotes: 1

Views: 121

Answers (2)

Steve Todd
Steve Todd

Reputation: 1270

sender is always the object that triggered the event, so casting it to TextBox and then setting the value does what you want, but OmegaMan's solution needs less XAML and is better for re-usability.

if (sender is TextBox zipCtrl)
{
    zipCtrl.Text = "";
}

Upvotes: 1

ΩmegaMan
ΩmegaMan

Reputation: 31596

Create a user control which has a textbox and handles this requirement with the code you wrote inplace in the custom control.

Then re-use the new control as needed.

Upvotes: 3

Related Questions