2011-06-02 74 views
1

我試圖使取決於某些屬性(例如)數據模型的ValidationRule。ValidationRule綁定到Windows上下文

我有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}" 

這不起作用,因爲:

COS的依賴對象是不符合邏輯樹的一部分 ,所以你不能使用 的ElementName或DataContext的作爲內部數據綁定的源 。

但爲什麼它不是邏輯樹的一部分?

2)如何可以結合我的有效性規則的屬性,一些動態資源

UPDATE 在觀看了更好的解決方案我做了這個:

  1. 添加事件,檢查的唯一性到有效性規則
  2. 將處理程序添加到窗口類
  3. 從ValidationRule引發事件並檢查EventArgs的結果

回答

0

什麼是你綁定到,你試圖添加驗證。我如何通過讓綁定的對象實現IDataErrorInfo來處理這個問題。然後,我可以將我的錯誤處理放在該對象中,並可以訪問我需要的任何東西。如果你在控制你綁定的對象,這將是可能的。

+0

我無法爲bisness對象實現IDataErrorInfo – karabara 2011-06-03 06:06:51

+0

您是否可以將Business Object包裝在ViewModel中並通過它來實現它? – 2011-06-03 18:30:06