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.
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" />
...
使用 StringFormat=C 定义文本框。
<TextBox Text="{Binding Path=TextProperty, StringFormat=C}"/>
sender is Control for which event is fired:
private void OnCurrencyTextBox_PreviewTextInput(object sender,
TextCompositionEventArgs e)
{
((TextBox)sender).Text = FormattedCurrency(((TextBox)sender).Text);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.