【问题标题】:One Event for Multiple TextBoxes WPF多个文本框 WPF 的一个事件
【发布时间】:2017-06-30 09:25:27
【问题描述】:

我有多个 (> 10) 用于存储货币值的文本框。当用户键入时,我想将输入格式化为货币。

我可以为每个 TextBox 创建一个方法,但这意味着创建 > 10 个方法。我宁愿创建多个 TextBoxes 可以使用的一种方法。例如:

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

但是,这仅适用于名为 CurrencyTextBox 的文本框。当然,如果密钥是数字等,还需要进行其他检查,但出于这个问题的目的,我关注的是如何将一种方法应用于多个文本框。

【问题讨论】:

标签: c# wpf


【解决方案1】:

将 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" />
...

【讨论】:

    【解决方案2】:

    使用 StringFormat=C 定义文本框。

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

    【讨论】:

    • 这是最好的方法。如果用户想要自定义格式,则可以实现转换器。
    【解决方案3】:

    sender 控制触发哪个事件:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-23
      • 1970-01-01
      • 2012-11-04
      • 1970-01-01
      • 2010-10-20
      • 1970-01-01
      相关资源
      最近更新 更多