1

我有以下代码。该窗口有一个文本框和一个复选框。如果我专注于复选框以外的任何内容并输入类似 123-456 的内容,那么对于每个字符PreviewKeyDownPreviewTextInput正在触发。

但是,如果我将焦点放在复选框上,然后键入 123-456,那么PreviewKeyDown会为所有字符PreviewTextInput触发 ,而仅针对 123456 触发并且不会针对-. 连字符由复选框处理,而不是传递给PreviewTextInput. 有没有办法得到连字符PreviewTextInput

public Window1()
{
    InitializeComponent();
    TextCompositionManager.AddTextInputHandler(this, new TextCompositionEventHandler(Window_PreviewTextInput));
}

private void Window_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{

}

private void Window_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
}
4

1 回答 1

1

我找到了一种方法来做到这一点,但我想从专家那里知道我的解决方案是否存在问题或更好的方法来做到这一点。

在窗口的 KeyDown 事件中,我将 Handled 标记为 false。该复选框在 KeyDown 和窗口的 KeyDown 中将 Handled 设置为 true,我将其设置为 false,这将调用 PreviewTextInput,因为事件仍需要处理。

public Window1()
        {
            InitializeComponent();
            TextCompositionManager.AddPreviewTextInputStartHandler(this, new TextCompositionEventHandler(Window_PreviewTextInput));
            this.AddHandler(Window.KeyDownEvent, new System.Windows.Input.KeyEventHandler(Window_KeyDown), true);
        }

private void Window_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
        }

private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            e.Handled = false;
        }
于 2009-09-30T20:37:08.660 回答