【问题标题】:MVVM Light e.Handled does not keep the stateMVVM Light e.Handled 不保持状态
【发布时间】:2016-07-27 21:03:55
【问题描述】:

我在我的 wpf 应用程序项目中使用 mvvm light。为了收听事件,我使用了来自 MVVM Light 库的EventToCommand

控制代码如下:

<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>

以及在 ViewModel 中实现的代码:

 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 不保留下一个事件处理程序的状态?

【问题讨论】:

    标签: c# wpf mvvm


    【解决方案1】:

    为什么你认为它没有保存它?这只是一个不同的事件,它们之间没有交流。所以你无法在TextChanged 事件中获得e.Handled== true

    【讨论】:

    • 所以它不会将e.Handled 传递给下一个处理程序?
    • @zero_coding 是的,它没有。验证和 PropertyChanged 事件没有直接连接。 WPF 检查错误并将它们添加到对象绑定对象(在本例中为 TextBox)。而propertychanged 事件告诉你有一些变化。如果您想检查错误是否受控,请尝试检查 Validation.Errors Attached Property
    • 非常感谢您的帮助。
    【解决方案2】:

    您不能将e.Handled = true 与您现在正在做的不同事件混为一谈。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多