Pergunta

Eu tenho um aplicativo WPF com alguma caixa de texto para entrada decimal.

Eu gostaria que, quando pressione a tecla "Dot" (.) No teclado numérico do teclado PC, ele envie o separador decimal correto.

Por exemplo, no idioma italiano, o separador decimal é "vírgula" (,) ... é possível definir a tecla "Dot" para enviar o personagem "vírgula" quando pressionado?

Foi útil?

Solução

Outras dicas

Embora você possa definir a localidade do conversor padrão no WPF, conforme sugerido por Mamta Dalal, não é suficiente para converter a tecla "decimal" Pressione para a sequência correta. Este código exibirá o símbolo da moeda correto e o formato de data/hora nos controles ligados a dados

//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
}

Descobri que o manuseio do evento VisuewKeyDown em toda a janela é um pouco mais limpo do que a caixa de texto específica (seria melhor se pudesse ser aplicado em todo o aplicativo).

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});
            }
        }
    }
}

Se alguém puder criar uma maneira de definir em todo o aplicativo ...

Rapido e sujo:

   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;
        }
    }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top