Event to take control's text via event args

2019-08-26 17:02发布

问题:

What is the event I should subscribe to in order to get TextBox's Text in the event args?

I've tried PreviewTextInput, but if input string is, for example, "122." the box's (see code) text is without the dot but eventArgs.Text is "." and the input string validating successfully and TextBox.Text is "122..". What I want to do is to validate if the input string is decimal by calling decimal.TryParse.

private void OnPreviewTextInput(object sender, TextCompositionEventArgs eventArgs)
{
    var box = sender as TextBox;
    if (box == null) return;

    eventArgs.Handled = !ValidationUtils.IsValid(box.Text + eventArgs.Text);
}

回答1:

You may try something like this:

private void OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
    var textBox = (TextBox)sender;
    var text = textBox.Text.Insert(textBox.CaretIndex, e.Text);
    decimal number;
    if (!decimal.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out number))
    {
        e.Handled = true;
    }
}