2012-05-17 42 views
3

就越多的Validation.Error事件触发顺序而言,我越来越奇怪。根据文档here,,数据绑定引擎首先删除可能已添加到绑定元素的Validation.Errors附加属性的任何ValidationError。因此,对于删除的ValidationErrorEvent应先于新增解雇,但奇怪的是在我的情况下删除事件之前的新增事件被炒鱿鱼。这是我正在使用的代码。奇怪的Validation.Error事件触发顺序 - 在Removed之前添加了触发器

XAML

<TextBox Grid.Row="3" Grid.Column="1" Name="txtGroupsPerRow" > 
    <TextBox.Text> 
     <Binding Path="StandardRack.NoOfGroupsPerRow" ValidatesOnDataErrors="True" NotifyOnValidationError="True" 
       UpdateSourceTrigger="PropertyChanged"> 
      <Binding.ValidationRules> 
       <gs:NumericValidationRule PropertyName="No Of Groups Per Row"/> 
      </Binding.ValidationRules> 
     </Binding> 
    </TextBox.Text> 
</TextBox> 

代码隐藏

private RoutedEventHandler _errorEventRoutedEventHandler; 
private void UserControl_Loaded(object sender, RoutedEventArgs e) { 
    _errorEventRoutedEventHandler = new RoutedEventHandler(ExceptionValidationErrorHandler); 
    this.AddHandler(System.Windows.Controls.Validation.ErrorEvent, _errorEventRoutedEventHandler, true); 
} 

private void UserControl_Unloaded(object sender, RoutedEventArgs e) { 
    this.RemoveHandler(System.Windows.Controls.Validation.ErrorEvent, _errorEventRoutedEventHandler); 
    _errorEventRoutedEventHandler = null; 
} 

//Added fired before Removed 
private void ExceptionValidationErrorHandler(object sender, RoutedEventArgs e) { 
    if (validationErrorEvent.Action == ValidationErrorEventAction.Added) { 
     viewModel.AddValidationError(propertyPath, validationErrorEvent.Error.ErrorContent.ToString()); 
    } 
    else if (validationErrorEvent.Action == ValidationErrorEventAction.Removed) { 
     viewModel.RemoveValidationError(propertyPath); 
    } 
} 

有没有人碰到这个问题,或者是有什么错我的代码?

+0

我刚碰到同样的问题! –

回答

1

望着source code,除去之前增加一个新的验证错误的步骤,一个老

精心有序的,以避免经历一个“没有错误”状态,而另一个

更换一个错误
+0

我认为我的应用程序遭受同样的错误。如果我在文本框中输入一个无效的值,则事件触发正确,然后当我输入另一个非有效值时,首先获取EventAction.added事件,然后获取EventAction.removed,这会将文本解析为完全有效的。我怎样才能解决这个问题? – Lorgarn

0

记住fractor的答案,你可以尝试做一个小的解决方法。 创建一些反将代表验证控件的错误数:

int errorCounter = 0; 
private void TextBox_Error(object sender, ValidationErrorEventArgs e) 
{ 
    var tb = sender as TextBox; 
    if (tb != null) 
    { 
     errorCounter += (e.Action == ValidationErrorEventAction.Added) ? 1 : -1; 
     //here do whatever you want to with you stored information about error 
     someControl.IsEnabled = !(errorCounter > 0); 
    } 
} 

我知道这是有点老问题,但我希望这将有助于。

-1

您可以使用此事件来确定错误状态的更改,但由于它们出现的顺序不正确(出于很好的原因,请参见fractor的答案),您应该阅读Validation.HasErrors属性。

var hasErrors = (bool)GetValue(Validation.HasErrorProperty);

为此在同一个处理程序,它永远是正确的。