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

2024-03-08

我们的应用程序中有几个数据对象最终绑定到网格。我们让它们实现 IDataErrorInfo 接口,以便通过向属性添加错误消息,我们可以看到行标题更改样式并且 DataGridCell 获得红色边框。一切都很好。

我们现在有一个额外的要求,即我们不仅有错误,而且有错误和警告。警告与错误相同,只是它们应该产生黄色边框而不是红色边框。

我们基于 IDataErrorInfo 创建了一个新接口 IDataWarningInfo。工作正常。我可以在运行时访问它,我有 RowValidatiionRules 可以访问它,并设置黄色行标题而不是红色行标题、适当的工具提示等。我缺少的是设置给定单元格边框的能力为黄色,因为它已数据绑定到属性,且该属性具有警告消息。

我可以通过将数据绑定属性的名称传递回接口来检索该警告消息;我怀疑验证代码在幕后正是这样做的。我缺少的是如何在 XAML 中执行此操作。具体来说,我认为我需要将样式应用于单元格,其中该样式包含一个 DataTrigger,它以某种方式将 DataBound 属性的名称传递给对象,然后如果结果与 null 不同,则将一些 Setter 应用于单元格。

有谁知道如何实现这一目标?


我有一个带有附加属性的类,需要验证该属性的依赖属性。然后,它使用 DependencyPropertyDescriptor 将事件附加到该 dependencyproperty 的更改事件。

然后,当它发生更改时,它会查看绑定,运行验证规则并设置属性的验证错误,而不提交绑定。

public static class ValidatingControlBehavior
{
    /// <summary>
    /// Defines the ValidatingProperty dependency property.
    /// </summary>
    public static readonly DependencyProperty ValidatingPropertyProperty = DependencyProperty.RegisterAttached("ValidatingProperty", typeof(DependencyProperty), typeof(ValidatingControlBehavior), 
        new PropertyMetadata(ValidatingControlBehavior.ValidatingPropertyProperty_PropertyChanged));

    /// <summary>
    /// Attaches the event.
    /// </summary>
    /// <param name="control">The control.</param>
    /// <param name="dependencyProperty">The dependency property.</param>
    private static void AttachEvent(Control control, DependencyProperty dependencyProperty)
    {
        DependencyPropertyDescriptor.FromProperty(dependencyProperty, typeof(Control)).AddValueChanged(control, ValidatingControlBehavior.Control_PropertyChanged);
        control.ForceValidation(dependencyProperty);
    }

    /// <summary>
    /// Handles the PropertyChanged event of the Control control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    private static void Control_PropertyChanged(object sender, EventArgs e)
    {
        Control control = (Control)sender;
        control.ForceValidation(ValidatingControlBehavior.GetValidatingProperty(control));
    }

    /// <summary>
    /// Forces the validation.
    /// </summary>
    /// <param name="dependencyObject">The dependency object.</param>
    /// <param name="dependencyProperty">The dependency property.</param>
    private static void ForceValidation(this DependencyObject dependencyObject, DependencyProperty dependencyProperty)
    {
        BindingExpressionBase expression = BindingOperations.GetBindingExpressionBase(dependencyObject, dependencyProperty);
        Collection<ValidationRule> validationRules;
        if (expression != null)
        {
            MultiBinding multiBinding;
            Binding binding = expression.ParentBindingBase as Binding;
            if (binding != null)
            {
                validationRules = binding.ValidationRules;
            }
            else if ((multiBinding = expression.ParentBindingBase as MultiBinding) != null)
            {
                validationRules = multiBinding.ValidationRules;
            }
            else
            {
                return;
            }
            for (int i = 0; i < validationRules.Count; i++)
            {
                ValidationRule rule = validationRules[i];
                ValidationResult result = rule.Validate(dependencyObject.GetValue(dependencyProperty), CultureInfo.CurrentCulture);
                if (!result.IsValid)
                {
                    Validation.MarkInvalid(expression, new ValidationError(rule, expression.ParentBindingBase, result.ErrorContent, null));
                    return;
                }
            }
            Validation.ClearInvalid(expression);
        }
    }

    /// <summary>
    /// Detaches the event.
    /// </summary>
    /// <param name="control">The control.</param>
    /// <param name="dependencyProperty">The dependency property.</param>
    private static void DetachEvent(Control control, DependencyProperty dependencyProperty)
    {
        DependencyPropertyDescriptor.FromProperty(dependencyProperty, typeof(Control)).RemoveValueChanged(control, ValidatingControlBehavior.Control_PropertyChanged);
    }

    /// <summary>
    /// Handles the PropertyChanged event of the ValidatingPropertyProperty control.
    /// </summary>
    /// <param name="d">The source of the event.</param>
    /// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
    private static void ValidatingPropertyProperty_PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        Control control = d as Control;
        if (control != null)
        {
            if (e.OldValue != null)
            {
                ValidatingControlBehavior.DetachEvent(control, (DependencyProperty)e.OldValue);
            }
            if (e.NewValue != null)
            {
                ValidatingControlBehavior.AttachEvent(control, (DependencyProperty)e.NewValue);
            }
        }
    }

    /// <summary>
    /// Gets the validating property.
    /// </summary>
    /// <param name="control">The control.</param>
    /// <returns>
    /// Dependency property.
    /// </returns>
    public static DependencyProperty GetValidatingProperty(Control control)
    {
        return (DependencyProperty)control.GetValue(ValidatingControlBehavior.ValidatingPropertyProperty);
    }

    /// <summary>
    /// Sets the validating property.
    /// </summary>
    /// <param name="control">The control.</param>
    /// <param name="validatingProperty">The validating property.</param>
    public static void SetValidatingProperty(Control control, DependencyProperty validatingProperty)
    {
        control.SetValue(ValidatingControlBehavior.ValidatingPropertyProperty, validatingProperty);
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在没有验证的情况下模仿验证行为 的相关文章

随机推荐

  • 如何在 Keras 中故意过度拟合卷积神经网络以确保模型正常工作?

    我正在尝试诊断训练模型时导致精度低的原因 此时 我只想能够获得高训练精度 我可以稍后担心测试精度 过度拟合问题 如何调整模型以提高训练准确性 我想这样做是为了确保我在预处理步骤 洗牌 分割 标准化等 中没有犯任何错误 PARAMS drop
  • 如何相对于导致更改的点击事件对 ng-repeat 项目进行动画处理

    我正在尝试让用户从不同的项目集中选择项目 该项目应从单击的设置动画到所选项目列表中的新位置 在下面的演示中 将粉色框视为可用项目 将边框框视为所选项目列表 蓝色框 用户可以通过单击任一粉红色框来选择项目 angular module tes
  • 将 mysql 表转储到 CSV(stdout),然后将输出通过隧道传输到另一台服务器

    我正在尝试将数据库表移动到另一台服务器 复杂的是当前运行该表的机器几乎没有剩余空间 所以我正在寻找一个可以通过网络工作的解决方案 我尝试过从 src 机器上 mysqldumping 数据库并将其通过管道传输到目标 mysql 中 但我的数
  • 如何从 pytesseract 获得最佳结果?

    我正在尝试使用 OpenCV 和 Pytesseract 从图像中读取文本 但结果不佳 我有兴趣阅读文本的图像是 https www lubecreostorepratolapeligna it gb img logo png https
  • WPF 可编辑组合框验证

    我想要完成的是能够验证输入到可编辑组合框的新类别或从现有组合框的类别列表中选择一个类别 验证仅适用于 selectedItem 不适用于输入到 Text 的新文本 一旦我添加ValidateOnDataErrors True 对于 Comb
  • Visual Studio:立即窗口中的 IntelliSense 在哪里?

    看起来 立即 窗口需要一些像 IntelliSense 一样的活力 有人同意 不同意吗 这会在 VS2008 2010 中出现吗 如果您没有自动出现智能感知 请立即按 Ctrl 空格键 和乔尔一样 智能感知似乎是从封闭的窗口中进来的
  • 如何使用 scipy 和 lfilter 进行实时过滤?

    免责声明 我可能不太擅长 DSP 因此在使该代码正常工作时遇到的问题比我应有的要多 我需要在传入信号发生时对其进行过滤 我试图让这段代码工作 但到目前为止我还无法做到 参考文献scipy signal lfilter 文档 https do
  • 为什么 Msxml DocumentElement/SelectSingleNode 不返回任何内容?

    DocumentElement 属性和 SelectSingleNode 继续不返回任何内容 我已经验证 xml 加载正确 问题似乎出在 xml 解析器中 xml 没有任何命名空间 因此不需要设置 Private Function Pars
  • 使用 IntlDateFormatter 格式化 PHP 日期

    我注意到 当用 PHP 格式化日期时IntlDateFormatter http php net manual en class intldateformatter php根据语言的不同 结果可能会有很大不同 例子 formatter ne
  • 不同窗口大小的滚动总和

    我正在寻找随着窗口大小变化计算滚动总和的最快方法 我使用下面的代码 但是对于长度为 1M 的向量来说 它太慢了 Thanks set seed 1 n 10L x runif n window pmin sample 1 10 n TRUE
  • Twbs分页无法加载数据表中的新页面数据

    您好 我正在处理分页 发现当我单击第二页时无法从 twbs 插件加载数据 事实上 该方法是从 ajax 调用中调用的 但数据表数据仍然相同 有人可以告诉我该怎么做才能用服务器上的新数据填充表格 查看 thymeleaf 和 spring b
  • 更新的运行状况检查是否会导致 App Engine 部署失败?

    我们将谷歌应用程序引擎运行状况检查从旧版本更新为新版本 现在我们的部署失败了 该项目的其他内容没有改变 我们测试了默认设置 然后进行了扩展检查以防万一 这是错误 ERROR gcloud app deploy Error Response
  • Firebase 存储 getMetadata() 问题

    我一直在尝试从 Firebase Storage 获取图像文件的元数据 md5hash 并检查它是否与用户手机上图像文件的 md5hash 不相等 问题是 即使哈希值相同 我得到的结果也是不同的 这是我试图获取元数据并进行比较的代码 for
  • 测试所有对象是否具有相同的成员值

    我有一个简单的课程python questions tagged python class simple object def init self theType someNum self theType theType self some
  • ListView 滚动 - 一项一项

    我有一个必须一次显示 4 个项目的 ListView 我必须一项一项地滚动 用户滚动 ListView 后 我必须重新调整滚动以适合 4 个项目 我的意思是 我无法将某个项目显示一半 还有一个问题 有没有办法获取当前ListView的scr
  • 如何为 Azure 表存储 REST 请求生成 SharedKeyLite

    我尝试使用 Postman 调用 Azure 表存储 但不断收到 服务器无法验证请求 确保值 授权标头格式正确 包括签名 我在 Postman 中用于预调用脚本的代码如下 var storageAccount mystorageaccoun
  • Python selenium:显式等待加载两个元素之一

    有没有一种方法可以让我等待两个元素之一加载到硒中 我正在使用显式等待 到目前为止 还无法找到解决方案 简单地做 WebDriverWait driver 5 until lambda driver driver find element B
  • jQuery Mobile 背景图像未显示在全屏 iPad Web 应用程序上

    我已经在 data role page 元素上设置了背景 如下所示 div style background transparent url img background jpg no repeat 它在桌面浏览器和 iPad safari
  • 有没有类似Codecademy for Java的东西[关闭]

    Closed 这个问题是无关 help closed questions 目前不接受答案 有谁知道像这样的网站代码学院 http www codecademy com专注于 Java 编程教学 Codeacademy com 使用 Java
  • 在没有验证的情况下模仿验证行为

    我们的应用程序中有几个数据对象最终绑定到网格 我们让它们实现 IDataErrorInfo 接口 以便通过向属性添加错误消息 我们可以看到行标题更改样式并且 DataGridCell 获得红色边框 一切都很好 我们现在有一个额外的要求 即我