[英]One Event for Multiple TextBoxes WPF
我有多個(> 10)個用於存儲貨幣價值的文本框。 當用戶輸入時,我想將輸入格式化為貨幣。
我可以為每個 TextBox 創建一個方法,但這意味着創建 > 10 個方法。 我寧願創建一種多個 TextBox 可以使用的方法。 例如:
private void OnCurrencyTextBox_PreviewTextInput(object sender,
TextCompositionEventArgs e)
{
CurrencyTextBox.Text = FormattedCurrency(CurrencyTextBox.Text);
}
但是,這僅適用於名為CurrencyTextBox
的 TextBox 。 當然,如果鍵是數字等,還需要進行其他檢查,但出於這個問題的目的,我專注於如何將一種方法應用於多個文本框。
將 sender 參數轉換為TextBox
:
private void OnCurrencyTextBox_PreviewTextInput(object sender,
TextCompositionEventArgs e)
{
TextBox textBox = (TextBox)sender;
textBox.Text = FormattedCurrency(textBox.Text);
}
然后,您可以對所有TextBox
元素使用相同的事件處理程序:
<TextBox x:Name="t1" PreviewTextInput="OnCurrencyTextBox_PreviewTextInput" />
<TextBox x:Name="t2" PreviewTextInput="OnCurrencyTextBox_PreviewTextInput" />
...
使用 StringFormat=C 定義文本框。
<TextBox Text="{Binding Path=TextProperty, StringFormat=C}"/>
sender 是觸發哪個事件的控件:
private void OnCurrencyTextBox_PreviewTextInput(object sender,
TextCompositionEventArgs e)
{
((TextBox)sender).Text = FormattedCurrency(((TextBox)sender).Text);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.