Reputation: 2983
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.
Upvotes: 0
Views: 1240
Reputation: 169400
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" />
...
Upvotes: 4
Reputation: 583
Define textbox with StringFormat=C.
<TextBox Text="{Binding Path=TextProperty, StringFormat=C}"/>
Upvotes: 2
Reputation: 3161
sender is Control for which event is fired:
private void OnCurrencyTextBox_PreviewTextInput(object sender,
TextCompositionEventArgs e)
{
((TextBox)sender).Text = FormattedCurrency(((TextBox)sender).Text);
}
Upvotes: 0