7

我有一个带有一些用于十进制输入的文本框的 Wpf 应用程序。

我希望当我在 pc 键盘的数字小键盘上按“点”键 (.) 时,它会发送正确的小数分隔符。

例如,在意大利语中,小数点分隔符是“逗号”(,)...是否可以设置“点”键在按下时发送“逗号”字符?

4

2 回答 2

6

又快又脏:

   private void NumericTextBox_KeyDown(object sender, KeyEventArgs e) {
        if (e.Key == Key.Decimal) {
            var txb = sender as TextBox;
            int caretPos=txb.CaretIndex;
            txb.Text = txb.Text.Insert(txb.CaretIndex, System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator);
            txb.CaretIndex = caretPos + 1;
            e.Handled = true;
        }
    }
于 2011-05-14T11:54:57.337 回答
6

尽管您可以按照 Mamta Dalal 的建议在 WPF 中设置默认转换器区域设置,但将“十进制”按键转换为正确的字符串是不够的。此代码将在数据绑定控件上显示正确的货币符号和日期/时间格式

//Will set up correct string formats for data-bound controls,
// but will not replace numpad decimal key press
private void Application_Startup(object sender, StartupEventArgs e)
{
    //Among other settings, this code may be used
    CultureInfo ci = CultureInfo.CurrentUICulture;

    try
    {
        //Override the default culture with something from app settings
        ci = new CultureInfo([insert your preferred settings retrieval method here]);
    }
    catch { }
    Thread.CurrentThread.CurrentCulture = ci;
    Thread.CurrentThread.CurrentUICulture = ci;

    //Here is the important part for databinding default converters
    FrameworkElement.LanguageProperty.OverrideMetadata(
            typeof(FrameworkElement),
            new FrameworkPropertyMetadata(
                XmlLanguage.GetLanguage(ci.IetfLanguageTag)));
    //Other initialization things
}

我发现在窗口范围内处理 previewKeyDown 事件比特定于文本框要干净一些(如果可以在应用程序范围内应用它会更好)。

public partial class MainWindow : Window
{
    public MainWindow()
    {
        //Among other code
        if (CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator != ".")
        {
            //Handler attach - will not be done if not needed
            PreviewKeyDown += new KeyEventHandler(MainWindow_PreviewKeyDown);
        }
    }

    void MainWindow_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Decimal)
        {
            e.Handled = true;

            if (CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator.Length > 0)
            {
                Keyboard.FocusedElement.RaiseEvent(
                    new TextCompositionEventArgs(
                        InputManager.Current.PrimaryKeyboardDevice,
                        new TextComposition(InputManager.Current,
                            Keyboard.FocusedElement,
                            CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator)
                        ) { RoutedEvent = TextCompositionManager.TextInputEvent});
            }
        }
    }
}

如果有人能想出一种在应用程序范围内设置它的方法......

于 2012-12-05T10:50:16.967 回答