2010-09-03 18 views
0

我有一個在實體元數據類中設置了一些驗證的表單。然後通過VM將實體實例綁定到UI。東西如下:爲什麼驗證錯誤顯示在validationSummary中?

XAML中,如:

<Grid x:Name="LayoutRoot"> 
      <StackPanel VerticalAlignment="Top"> 
       <input:ValidationSummary /> 
      </StackPanel> 
     <TextBox Text="{Binding Name, Mode=TwoWay}" /> 
     <ComboBox x:Name="xTest" ItemsSource="{Binding MyList}" 
       SelectedItem="{Binding MyItem,Mode=TwoWay, 
       DisplayMemberPath="MyName" 
       ValidatesOnDataErrors=True, 
       ValidatesOnNotifyDataErrors=True, 
       ValidatesOnExceptions=True, 
       NotifyOnValidationError=True,UpdateSourceTrigger=Explicit}" /> 
     </Grid> 

代碼隱藏,如:

public MyForm() 
{ 
    InitializeComponent(); 
    this.xTest.BindingValidationError +=new EventHandler<ValidationErrorEventArgs>((s,e)=>{ 

    BindingExpression be = this.xTest.GetBindingExpression(ComboBox.SelectedItemProperty); 
    be.UpdateSource(); 

    if (e.Action == ValidationErrorEventAction.Added) 
    ((ComboBox)s).Foreground = new SolidColorBrush(Colors.Red); 
    }); 
} 

元數據,如:

[Required] 
public string Name { get; set; } 

[RequiredAttribute] 
public int MyItemID { get; set; } 

但在運行應用程序時,我什麼都沒顯示在價值總結。 對於CombBox,即使有錯誤,看起來像BindingValidationError事件永遠不會被解僱。 如何解決它?

回答

2

你爲什麼使用Explicit UpdateSourceTrigger?

當綁定更新源對象時,Silverlight驗證發生在綁定框架內部。你有這種方式,不會有一個綁定驗證錯誤,因爲你永遠不會告訴綁定來更新源對象。那麼,實際上你是這樣做的,但它發生在驗證錯誤事件處理程序內部。你已經寫了雞和蛋的代碼。

  • 刪除您的綁定上的UpdateSourceTrigger或將其設置爲Default
  • 刪除對BindingExpression.UpdateSource的明確呼叫。
  • 刪除將組合框前景設置爲紅色 - 您正在使用NotifyOnValidationError=True,這消除了手動給控件着色的任何需要。
  • 從綁定

所以你的XAML刪除DisplayMemberPath

<Grid x:Name="LayoutRoot"> 
    <StackPanel VerticalAlignment="Top"> 
     <input:ValidationSummary /> 
     <ComboBox x:Name="xTest" ItemsSource="{Binding MyList}" 
       SelectedItem="{Binding MyItem, 
       Mode=TwoWay, 
       ValidatesOnDataErrors=True, 
       ValidatesOnNotifyDataErrors=True, 
       ValidatesOnExceptions=True, 
       NotifyOnValidationError=True}" /> 
     </StackPanel> 
</Grid> 

並且代碼:

public MyForm() 
{ 
    InitializeComponent(); 
    // you don't need anything here to have the validations work 
} 
+0

謝謝。完成你的建議:1.保持DisplayMemberPath,因爲MyName是實體MyItem的一個屬性。 2.在xaml中添加所有驗證選項。 3.移除事件BindingValidationError的代碼。然後再次運行該應用程序。結果是:我可以在VM中的Entity.ValidationErrors中獲得驗證錯誤(我使用消息框來顯示它進行測試),但無法在ValidationSummary中獲取它。 – KentZhou 2010-09-08 13:51:17

+0

你在你的例子中綁定了DisplayMemberPath。並且綁定標記擴展中沒有DisplayMemberPath選項。 – 2010-09-08 13:56:18

+0

要使您的驗證摘要正常工作,請將其移動到與ComboBox相同的父容器中(編輯我的答案)。 – 2010-09-08 13:58:15

相關問題