2010-11-10 33 views
2

我使用自定義驗證規則來驗證我的數據。但我無法訪問/確定屬性值。WPF從自定義驗證規則中獲取實際值

這裏是我的代碼

public class MandatoryRule: ValidationRule 
{ 
    public MandatoryRule() 
    { 
     ValidationStep = System.Windows.Controls.ValidationStep.UpdatedValue; 
    } 

    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) 
    { 
     BindingExpression exp = value as BindingExpression; 

     if (value == null) 
      return new ValidationResult(true, null); 

     return new ValidationResult(true, null); 
    } 
} 

我需要設置ValidationStep到UpdatedValue(用於進一步的業務邏輯)

於是問題來了:我不知道什麼是屬性值?因爲:

  1. 它是一個通用的驗證,無法綁定到特定模型
  2. 在驗證方法的參數值是BindingExpression

所以,我怎麼能讀的真正價值?

感謝

回答

1

最後,我想出了這個主意。

創建一個類DummyObject:DependencyObject。 創建一個公共靜態DependencyProperty DummyProperty。

然後創建一個新的數據綁定,從(值爲BindingExpression).ParentBinding複製源,綁定路徑,元素名稱,轉換器等。

將新的數據綁定目標設置爲dummyobject。

然後用結合UpdateTarget()

現在你可以從dummyproperty訪問值。

1

有同樣的問題,並且出現了這個問題,加里的答案似乎是要走的路,但它缺乏源代碼。所以這是我的解釋。

public class BindingExpressionEvaluator : DependencyObject 
{ 
    public object Value 
    { 
     get { return (object)GetValue(ValueProperty); } 
     set { SetValue(ValueProperty, value); } 
    } 

    public static readonly DependencyProperty ValueProperty = 
     DependencyProperty.Register("ValueProperty", typeof(object), 
     typeof(BindingExpressionEvaluator), new UIPropertyMetadata(null)); 

    public static object Evaluate(BindingExpression expression) 
    { 
     var evaluator = new BindingExpressionEvaluator(); 
     var binding = new Binding(expression.ParentBinding.Path.Path); 
     binding.Source = expression.DataItem; 
     BindingOperations.SetBinding(evaluator, BindingExpressionEvaluator.ValueProperty, binding); 
     var value = evaluator.Value; 
     BindingOperations.ClearBinding(evaluator, BindingExpressionEvaluator.ValueProperty); 
     return value; 
    } 
}