2016-07-27 33 views
-1

我在我的wpf应用程序项目中使用mvvm light。要收听活动,我正在使用MVVM Light库中的EventToCommandMVVM Light e.Handled不保持状态

控制代码看起来如下:

<TextBox x:Name="Scannerport" 
      Grid.Row="1" 
      Grid.Column="1" 
      Margin="15,10,40,10" 
      MinWidth="100" 
      FontSize="40" 
      MaxLength="2" 
      PreviewTextInput="Scaleport_OnPreviewTextInput" 
      VerticalContentAlignment="Center" 
      HorizontalContentAlignment="Center" 
      Text="{Binding ScannerPort, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True, NotifyOnValidationError=True}"> 
     <i:Interaction.Triggers> 
     <i:EventTrigger EventName="TextChanged"> 
      <cmd:EventToCommand Command="{Binding OnTextChanged}" 
           PassEventArgsToCommand="True" /> 
     </i:EventTrigger> 


     <rt:RoutedEventTrigger RoutedEvent="{x:Static Validation.ErrorEvent}"> 
      <cmd:EventToCommand Command="{Binding OnValidationError}" PassEventArgsToCommand="True" /> 
     </rt:RoutedEventTrigger> 

     </i:Interaction.Triggers> 
    </TextBox> 

并在视图模型的实现代码:

private void _OnTextChanged(TextChangedEventArgs e) 
    { 
     Debug.WriteLine(e.Handled); 
     if (ScalePort != 0 && ScannerPort != 0) 
     { 
     Disable = true; 
     return; 
     } 

     Disable = false; 
    } 

    private void _OnValidationError(ValidationErrorEventArgs e) 
    { 
     if (e.Action == ValidationErrorEventAction.Added) 
     { 
     Disable = true; 
     e.Handled = true; 
     } 
    } 

正如你可以在第二个方法看,我设置e.Handled = true再调试的过程中第一种方法e.Handled仍然是false? 为什么e.Handled不保留下一个事件处理程序的状态?

enter image description here enter image description here

回答

1

为什么你认为它没有保存呢?这只是一个不同的事件,他们不相互交流。所以你不能得到e.Handled== trueTextChanged事件。

+0

所以它不会传递'e.Handled'到下一个处理程序? –

+0

@zero_coding是的,它没有。验证和PropertyChanged事件不直接连接。 WPF检查错误并将它们添加到对象绑定的对象(本例中为TextBox)。而propertychanged事件告诉你有一些变化。 尝试检查[Validation.Errors Attached Property](https://msdn.microsoft.com/en-us/library/system.windows.controls.validation.errors(v = vs.110).aspx)如果您想要检查错误的控制。 – Shakra

+0

非常感谢您的帮助。 –

1

您不能将e.Handled = true与您正在做的事情等不同事件混合使用。

收听PreviewTextInput事件并设置e.Handled = true停止TextChanged事件再次被触发。