c# - WPF:验证与转换器

标签 c# wpf validation

使用转换器,我可以区分至少 4 种关于源值更新的行为:

  • 转换为正确的值(-> 更新源)
  • 返回 null(-> 表示错误)
  • 抛出异常并激活异常验证规则(->指示错误)
  • 返回 Binding.DoNothing (-> 不更新源,但不指示错误eiter)

ValidationRule , 我只能区分成功(-> 更新源)和失败(-> 不更新源),但我无法模拟与 Binding.DoNothing 关联的行为

有没有办法使用ValidationRule以类似于 Binding.DoNothing 的方式转换器的行为?

最佳答案

Converters 和 ValidationRules 的意图非常不同。转换器采用一个值并将其转换为另一个值。您提到的 4 个案例很常见,可以转换:做;做;说它是空的;爆炸;忽视。然而 ValidationRules 是/否 - 它们有效或无效。虽然有一个“忽略”选项可能有意义,但实际上没有。

语义上最接近的是在构造函数中设置 IsValid = true,但这并不是您想要的。

public override ValidationResult Validate(object value, CultureInfo cultureInfo) 
{
    try
    {
        // try normal setup/validation
    } 
    catch 
    {
        // handle exceptions, return false
    }
    // decide if you want to return false
    // return true (equivalent to nothing/ignore)
    return new ValidationResult(true, null);
}

我最后的想法是,如果您需要特殊情况,那么 try-catch 或其他逻辑就会崩溃。我唯一能想到的是在 ValidationRule 中进行类型检查,这很可疑,因为您正在创建不需要的依赖项,但会绕过这些问题。即

if (value is SpecialType)
{
    return new ValidationResult(true, null);
}

喂!

已更新

或者 IgnorableValidationRule 怎么样?

public class IgnorableValidationRule : ValidationRule
{
    public bool Ignore { get; set; } = false;

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        if (Ignore) return new ValidationResult(true, null);

        return new ValidationResult(false, "Why does everyone ignore me?");
    }
}

<TextBox.Text>
    <Binding Path="Data">
        <Binding.ValidationRules>
            <local:IgnorableValidationRule Ignore="True"/> <!-- na na -->
        </Binding.ValidationRules>
    </Binding>
</TextBox.Text>

关于c# - WPF:验证与转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33142176/

相关文章:

c# - 如何在不使用隐藏字段的情况下检测表单字段是否已更改

java - 工作单元模式的验证策略

c# - IIS 网址重写 : rewrite rule vs rewriteMap

c# - WPF 使列滑入位置 XAML

validation - Ember-Validations - 不要自动验证

wpf - 更改 InputLanguage 不起作用 WPF

c# - 构建错误: Reference PresentationCore could not be resolved

javascript - 如何本地化 asp :TextBox's placeholder by reading App_LocalResources file (. resx)

C# ListView.Columns.Add 的参数

c# - 如何自动打印tiff文件?