Event to take control's text via event args

痞子三分冷 提交于 2019-12-13 07:07:14

问题


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


来源:https://stackoverflow.com/questions/16817929/event-to-take-controls-text-via-event-args

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!