简体   繁体   中英

C#, How do I validate wpf textbox values?

TextBox:

<TextBox Text="{Binding Path=nSetting, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Name="tbSetting" />

Class:

public class FormLink
{
    private string _nSetting;

    public string nSetting 
    { 
        get 
        { 
            return this.validateNumberValue(this._nSetting, 256, 9999, 56);
        } 
        set
        {
            this._nSetting = this.validateNumberValue(value, 256, 9999, 56);
        } 
    }

    private string validateNumberValue(string number, int nMaxReturn, int nMaxParse, int nDefault)
    {
        int pNum = nMaxParse; 
        Int32.TryParse(number, out pNum);

        if (pNum == 0)
        {
            return nDefault.ToString();
        }
        else if (pNum < nMaxReturn)
        {
            return pNum.ToString(); 
        }
        else if (pNum > nMaxReturn)
        {
            return nMaxReturn.ToString();
        }
        else
        {
            return nDefault.ToString();
        }
    }
}  

How do I get this textbox to update properly?

Right now it updates to 256 if number > 256.. BUT... if I keep typing, it doesn't reset to 256. Also, after 10 characters, it resets to 0. I can also start typing 0s and keep going forever with no limit.

How do I get it to always update?
Why does it reset to 0 after the number is 10 characters long?
Why doesn't multiple 0s reset to 56 like I have coded?

There is a bug in the WPF 4 TextBox ( see my question ). The solution posted there works.

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