欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

WPF TextBox 正则验证 大于等于0 小于等于1 的两位小数

程序员文章站 2022-08-09 09:03:59
正则:^(0\.\d+|[1-9][0-9]|1)$ TextBox绑定正则验证

正则:^(0\.\d+|[1-9][0-9]|1)$

textbox绑定正则验证

<textbox x:name="txb"   maxlength="6" margin="1 0 0 0"  width="40" >
    <textbox.text>
        <binding path="opacity" validatesonexceptions="true" validatesondataerrors="true" stringformat="f2"            
          mode="twoway" updatesourcetrigger="propertychanged"                              >
            <binding.validationrules>
                <shared1:inventoryvalidationrule  inventorypattern="^(0\.\d+|[1-9][0-9]|1)$"/>
            </binding.validationrules>
       </binding>
    </textbox.text>
</textbox>

 

用到的inventoryvalidationrule类:

 public class inventoryvalidationrule : validationrule
    {
        #region properties

        public string inventorypattern { get; set; }

        #endregion properties

        #region methods

        public override validationresult validate(
                  object value, cultureinfo cultureinfo)
        {
            if (inventorypattern == null)
                return validationresult.validresult;

            if (!(value is string))
                return new validationresult(false,
               "inventory should be a comma separated list of model numbers as a string");

            string[] pieces = value.tostring().split(',');
            regex m_regex = new regex(inventorypattern);

            foreach (string item in pieces)
            {
                match match = m_regex.match(item);
                if (match == null || match == match.empty)
                    return new validationresult(
                      false, "invalid input format");
            }

            return validationresult.validresult;
        }

        #endregion methods
    }