简体   繁体   中英

WPF binding TextBox to integer property without throwing exception

I am binding TextBox.Text to int property:

<TextBox Text="{Binding Lines, UpdateSourceTrigger=PropertyChanged}" />

private int _lines = 10;
public int Lines
{
    get { return _lines; }
    set { _lines = value; }
}

everything works as expected with this simple code, there is even validation for the TextBox. There is however exception System.FormatException thrown in the Output log. My question is:
Is there elegant way to get rid of the exception without reimplementing almost everything myself?
By everything I mean validators, convertors, etc. simply ton of code that does not do anything but call Int32.TryParse instead of Int32.Parse . Not that exception thrown and handled by wpf would be a big problem, but full log makes finding actual problems much more difficult.

The question isn't all that clear, but I assume you are referring to an exception that occurs if the user enters invalid text (ie non-numeric, non-integer data).

AFAIK, WPF does not include a built-in control that restricts user input. So your options are:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM