【问题标题】:ValidationRule binding to windows contextValidationRule 绑定到 Windows 上下文
【发布时间】:2011-09-07 03:46:26
【问题描述】:

我正在尝试制作依赖于(例如)数据模型的某些属性的 ValidationRule。

我有带有验证器的 TextBox,它必须了解模型对象“Scheme”。我尝试将 Scheme 添加到 Resources 中,但这没有用。在我找到一些依赖依赖属性的解决方案之后。

根据这个http://dedjo.blogspot.com/2007/05/fully-binded-validation-by-using.html我做了:

/// <summary>
/// Check text value for emptiness and uniqueness
/// </summary>
public class EmptyAndUnique : ValidationRule
{
    public UniqueChecker UniqueChecker { get; set; }

    public string ErrorMessage { get; set; }

    public override ValidationResult Validate(object value,
        CultureInfo cultureInfo)
    {
        string inputString = (value).ToString();
        var result = new ValidationResult(true, null);

        // Check uniqueness
        if(this.UniqueChecker.Scheme.Factors.Any(f => f.Uid == inputString))
        {
            result = new ValidationResult(false, this.ErrorMessage);
            return result;
        }

        // Check emptiness
        if (inputString.Trim().Equals(string.Empty))
        {
            result = new ValidationResult(false, this.ErrorMessage);
            return result;
        }

        return result;
    }
}

/// <summary>
/// Wrapper for DependencyProperty. (trick)
/// </summary>
public class UniqueChecker : DependencyObject
{
    public static readonly DependencyProperty SchemeProperty =
        DependencyProperty.Register("Scheme", typeof(Scheme),
        typeof(UniqueChecker), new FrameworkPropertyMetadata(null));

    public Scheme Scheme
    {
        get { return (Scheme)GetValue(SchemeProperty); }
        set { SetValue(SchemeProperty, value); }
    }
}

这也不起作用。

1) 根据文章:

Scheme="{Binding      ElementName=expressionFactorEditorWindow, Path=Scheme}"

这不起作用,因为:

因为我们的依赖对象不是一部分 的逻辑树,所以你不能使用 ElementName 或 DataContext 作为源 用于内部数据绑定。

但是为什么它不是逻辑树的一部分呢?

2) 如何将我的 ValidationRule 的属性绑定到一些动态资源

更新 在寻找更好的解决方案时,我做了这个:

  1. 将检查唯一性的事件添加到 ValidationRule 中
  2. 将 Handler 添加到 Window 类中
  3. 从 ValidationRule 引发事件并从 EventArgs 检查结果

【问题讨论】:

    标签: wpf binding


    【解决方案1】:

    您尝试添加验证的对象是什么。我通常如何通过让我绑定的对象实现 IDataErrorInfo 来处理这个问题。然后我可以将我的错误处理放在那个对象中,并可以访问我需要的任何东西。如果您可以控制要绑定的对象,这将是可能的。

    【讨论】:

    • 我无法为 bisness 对象实现 IDataErrorInfo
    • 你能把你的业务对象包装在一个 ViewModel 中并通过它来实现它吗?
    猜你喜欢
    • 2011-05-19
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2011-07-30
    • 2011-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多