首页 > 解决方案 > 甚至在 OnPreviewKeyDown 事件之前在 wpf 文本框设置文本中输入中文

问题描述

我正在处理wpf遗留代码并发现奇怪的问题。我们正在使用从 Textbox 继承的自定义控件TimePicker。我们使用依赖属性来验证时间并使用默认值掩码,例如 _ : _。它适用于英文数字/字体,但如果我将语言输入更改为中文(在windows 10中),那么它的行为会有所不同。

class TimePicker : TextBox 

    static TimePicker()
    {
        // to receive coercion callback when Text property got changed
        InputMaskProperty = DependencyProperty.Register("InputMask",
           typeof(string), typeof(TimePicker),
           new FrameworkPropertyMetadata(InputMask_Changed,
           new CoerceValueCallback(OnCoerceValueChange)));
    }

一般的预期行为是,当用户敲击键盘时,会引发以下事件:

protected override void OnPreviewTextInput(TextCompositionEventArgs e)

在这里,只有我在上面的事件中设置了一些像 this.Text = "some value" 这样的值,而不是在下面的事件中调用,这实际上是 CoerceValueCallback:

  private static object OnCoerceValueChange(DependencyObject obj, object value)

如果我使用英文字体,一切都很好,它以上述方式调用,但如果我将 Windows 10 中的文化/输入语言更改为简体中文,则它直接设置this.Text值而不是调用 OnPreviewKeyDown , OnPreviewTextInput。任何建议请如何使逻辑独立于文化特定。

Xaml 代码如下:

           <External:TimePicker x:Name="StartTimePicker" InputMask="ii:ii" Grid.Row="1" Grid.Column="7" HorizontalAlignment="Left" 
                    Validation.Error="StartTimePickerError" Text="{Binding Path=StartTime, ValidatesOnDataErrors=True, 
                    UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True}" Width="50"
                    ToolTip="{Binding RelativeSource ={RelativeSource Self},Path=(Validation.Errors)[0].ErrorContent}">
            </External:TimePicker>

如果在事件OnPreviewKeyDown(KeyEventArgs e)下遇到e.Key也会抛出System.ExecutionEngineException

标签: c#.netwpfdependency-propertieschinese-locale

解决方案


推荐阅读