wpf鼠标捕获和焦点问题

时间:2014-04-29 13:13:40

标签: c# wpf keyboard-events lost-focus

我在userrcontrol中有一个文本框。 Usercopntrol具有String类型的Dependency属性“Text”。 usercontrol的Text属性绑定到TextBoxes Text属性。

public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
        "Text",
        typeof(String),
        typeof(MyTextControl),
        new FrameworkPropertyMetadata(String.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

xaml code ...

<TextBox
            x:Name="textbox1"
            Text="{Binding ElementName=MyTextControl, Path=Text, UpdateSourceTrigger=LostFocus}"
            ...
</TextBox>

请注意我们的应用程序中有理由认为UpdateSourceTrigger是LostFocus而不是PropertyChanged,以提供“撤消”功能。当焦点丢失时,文本更改将创建撤消步骤。

现在有一种情况是用户在应用程序内的另一个控件上点击Usercontrol外部。然后,“FocusLost” - 事件不会被wpf系统触发。 因此,我使用

Mouse.PreviewMouseDownOutsideCapturedElement   

这对于在这种情况下进行更新非常有用。

要捕获此事件,您需要在文本更改时设置鼠标捕获,并在发生单击时释放捕获。

private void OnTextBoxTextChanged(object sender, TextChangedEventArgs e)
{
    Mouse.Capture(sender as IInputElement);
}

private void OnPreviewMouseDownOutsideCapturedElement(object sender, MouseButtonEventArgs args)
    {
        var result= VisualTreeHelper.HitTest(this, args.GetPosition(this));
        if (result!= null)
        {
            // clicked inside of usercontrol, can keep capture, no work!
        }
        else
        {
            // outside of usercontrol, now store the text!
            if (_textbox != null)
            {
                _textbox.ReleaseMouseCapture();

                // do other text formatting stuff

                // assign the usercontrols dependency property by the current text
                Text = _textbox.Text;
            }
         }
      }

当实现此机制,并且用户单击文本框旁边的某处时,它会发现任何其他UIElement的PreviewGotKeyboardFocus之类的隧道事件不会因捕获而被触发。

private void OnPreviewGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
    {
        // never gets called!
        Debug.WriteLine("   OnPreviewGotKeyboardFocus"); 
    }

如何确保此机制不会阻止其他点击元素的PreviewGotKeyboardFocus事件?

0 个答案:

没有答案