0

I have multiple (> 10) TextBoxes that are used to store monetary values. As the user types, I want to format the input as a currency.

I could create one method for every TextBox but that means the creation of > 10 methods. I would rather create one method that multiple TextBoxes may use. For example:

private void OnCurrencyTextBox_PreviewTextInput(object sender, 
TextCompositionEventArgs e)
{
    CurrencyTextBox.Text = FormattedCurrency(CurrencyTextBox.Text);
}

However, this would only work for a TextBox named CurrencyTextBox. Of course there would need to be other checks for if the key is a digit etc but for the purpose of this question I am focusing on how I can apply one method to multiple TextBoxes.

1

3 Answers 3

4

Cast the sender argument to TextBox:

private void OnCurrencyTextBox_PreviewTextInput(object sender,
TextCompositionEventArgs e)
{
    TextBox textBox = (TextBox)sender;
    textBox.Text = FormattedCurrency(textBox.Text);
}

You can then use the same event handler for all TextBox elements:

<TextBox x:Name="t1" PreviewTextInput="OnCurrencyTextBox_PreviewTextInput" />
<TextBox x:Name="t2" PreviewTextInput="OnCurrencyTextBox_PreviewTextInput" />
...
Sign up to request clarification or add additional context in comments.

Comments

2

Define textbox with StringFormat=C.

<TextBox Text="{Binding Path=TextProperty, StringFormat=C}"/>

1 Comment

This is the best approach. and If the user want a custom format then a converter can be implemented.
0

sender is Control for which event is fired:

private void OnCurrencyTextBox_PreviewTextInput(object sender, 
TextCompositionEventArgs e)
{
    ((TextBox)sender).Text = FormattedCurrency(((TextBox)sender).Text);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.