如何约束TextBox

iLe*_*ing 4 wpf textbox constraints wpf-controls

如何设置a TextBox只获取某些值.例如,DateTime具有定义格式设置的输入框.

sta*_*son 6

如何使用WPF框架附带的绑定验证.

像这样创建一个ValidationRule

public class DateFormatValidationRule : ValidationRule
{
  public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
  {
     var s = value as string;
     if (string.IsNullOrEmpty(s))
        return new ValidationResult(false, "Field cannot be blank");
     var match = Regex.Match(s, @"^\d{2}/\d{2}/\d{4}$");
     if (!match.Success)
        return new ValidationResult(false, "Field must be in MM/DD/YYYY format");
     DateTime date;
     var canParse = DateTime.TryParse(s, out date);
     if (!canParse)
        return new ValidationResult(false, "Field must be a valid datetime value");
     return new ValidationResult(true, null);
  }
}
Run Code Online (Sandbox Code Playgroud)

然后将其添加到xaml中的绑定以及在字段无效时处理的样式.(如果您倾向于完全更改控件,也可以使用Validation.ErrorTemplate.)这个将ValidationResult文本作为工具提示,将框设置为红色.

    <TextBox x:Name="tb">
        <TextBox.Text>
            <Binding Path="PropertyThatIsBoundTo" UpdateSourceTrigger="PropertyChanged">
                <Binding.ValidationRules>
                    <val:DateFormatValidationRule/>
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
        <TextBox.Style>
            <Style TargetType="{x:Type TextBox}">
                <Style.Triggers>
                    <Trigger Property="Validation.HasError" Value="true">
                        <Setter Property="ToolTip"
                                Value="{Binding RelativeSource={RelativeSource Self},
                            Path=(Validation.Errors)[0].ErrorContent}"/>
                        <Setter Property="Background" Value="Red"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </TextBox.Style>
    </TextBox>
Run Code Online (Sandbox Code Playgroud)

建议采用样式并将其放入资源字典中,以便任何文本框在其自身验证失败时具有相同的外观.使XAML更加清洁.


the*_*jxc 5

http://www.codeproject.com/KB/WPF/wpfvalidation.aspx

<TextBox Text="{Binding Path=Name}" />
Run Code Online (Sandbox Code Playgroud)

还有一个功能.这只是检查字符串是否有内容.根据您要强制执行的确切格式,您的内容会更复杂:

public string Name
{
    get { return _name; }
    set
    {
        _name = value;
        if (String.IsNullOrEmpty(value))
        {
            throw new ApplicationException("Customer name is mandatory.");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)