c# - WPF 中文本框的条件验证规则?

标签 c# wpf validation

我有一个 WPF 应用程序,其 UI 包含一个复选框和一个文本框。复选框和文本框绑定(bind)到我的业务对象的属性。我一直在使用验证规则来验证用户输入,并且在大多数情况下,它们非常简单(检查值是否不为 null/空,检查值是否在特定范围内,等等)。 FWIW,这是我现有的 XAML:

<StackPanel>
    <CheckBox x:Name="requirePinNumberCheckBox" IsChecked="{Binding Path=RequirePinNumber, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">Require PIN number</CheckBox>
    <TextBox x:Name="pinNumberTextBox" Style="{StaticResource textBoxInError}" PreviewTextInput="pinNumberTextBox_PreviewTextInput">
        <TextBox.Text>
            <Binding Path="PinNumber" Mode="TwoWay" UpdateSourceTrigger="LostFocus">
                <Binding.ValidationRules>
                    <local:PinNumberValidationRule ValidationStep="RawProposedValue"/>
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>
</StackPanel>

我对文本框的验证规则很简单:

public class PinNumberValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        // make sure that the PIN number isn't blank
        if (string.IsNullOrEmpty(value.ToString()))
        {
            return new ValidationResult(false, "PIN number cannot be blank.");
        }
        else
        {
            return new ValidationResult(true, null);
        }
    }
}

与我的大多数其他验证方案不同,文本框的 ValidationRule 应该在复选框被选中时应用(或者更确切地说,当复选框绑定(bind)到的 bool 属性设置为 TRUE 时)。谁能告诉我如何实现这样的东西?谢谢!

最佳答案

您应该将验证逻辑从 UI (ValidationRule) 移开,并考虑在您的 ViewModel 中实现 IDataErrorInfo

一个好的开始是 this article .

然后你可以这样做:

<StackPanel>
    <CheckBox x:Name="requirePinNumberCheckBox" IsChecked="{Binding Path=RequirePinNumber, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">Require PIN number</CheckBox>
    <TextBox x:Name="pinNumberTextBox" 
             PreviewTextInput="pinNumberTextBox_PreviewTextInput"
             Text="{Binding PinNumber, ValidatesOnDataErrors=True}"
             ToolTip="{Binding (Validation.Errors).CurrentItem.ErrorContent, RelativeSource={RelativeSource Self}}" />
</StackPanel>
   public class ViewModel : IDataErrorInfo, INotifyPropertyChanged
    {
            private bool _requirePinNumber;
            public bool RequirePinNumber
            {
                get
                {
                    return this._requirePinNumber;
                }
                set
                {
                    this._requirePinNumber = value;
                    if (this.PropertyChanged != null)
                    {
                        this.PropertyChanged(this, new PropertyChangedEventArgs("RequirePinNumber"));
                        this.PropertyChanged(this, new PropertyChangedEventArgs("PinNumber"));
                    }
                }
            }

            private string _pinNumber;
            public string PinNumber 
            { 
                get
                {
                    return this._pinNumber;
                }
                set
                {
                    this._pinNumber = value;
                    if (this.PropertyChanged != null)
                    {
                        this.PropertyChanged(this, new PropertyChangedEventArgs("PinNumber"));
                    }
                }
            }

            public string Error
            {
                get 
                { 
                    throw new NotImplementedException(); 
                }
            }

            public string this[string columnName]
            {
                get 
                {
                    if (columnName == "PinNumber") 
                    {
                        if (this.RequirePinNumber && string.IsNullOrEmpty(this.PinNumber))
                        {
                            return "PIN number cannot be blank.";
                        }
                    }
                    return string.Empty;
                }
            }

            public event PropertyChangedEventHandler PropertyChanged;
        }

关于c# - WPF 中文本框的条件验证规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21141052/

相关文章:

c# - 找不到名为 'CloseButton' 的资源。资源名称区分大小写

c# - 基于 WPF 的桌面应用程序的推送通知服务?

c# - 使用 Entity Framework 作为数据访问层时,如何实现业务逻辑层?

ruby-on-rails - rails 3 : Validating Model uniqueness of Time within a Time Range

c# - MVP 模式中的用户输入验证

android - EditText inputtype "time"不支持冒号?

c# - 将 XML 文件转换为字符串类型

c# - 从 DTO 创建 BO 的模式/策略

c# - 如何取消合并单元格 EPPlus?

.net - 在没有验证的情况下模仿验证行为