wpf mouse capture and focus issue

I have a textbox inside a userrcontrol. The Usercopntrol has a Dependency property "Text" of type String. The usercontrol's Text property is bound to the TextBoxes Text property.

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>

PLease note There's reason in our app that the UpdateSourceTrigger is LostFocus and not PropertyChanged, to provide "undo"-feature. A text change will create an Undo step, when the focus is lost.

Now there's a case when the user clicks outside of the Usercontrol, on another control inside the app. "FocusLost"-event is NOT fired by the wpf system then. Therefore, I use the

Mouse.PreviewMouseDownOutsideCapturedElement   

which figured out to be useful for updating in such cases.

To catch this event, you need to set mouse capture when the text changes, and releasing capture when the click occurs.

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

When this mechanism is implemented, and the user clicks somewhere aside the textbox, it figured out that tunnelling events like PreviewGotKeyboardFocus of any other UIElement doesn't get fired because of the capture.

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

How can I make sure this mechanism doesn't block the PreviewGotKeyboardFocus event for other clicked elements ?

链接地址: http://www.djcxy.com/p/44936.html

上一篇: 如何使pycharm在我的例外中断

下一篇: wpf鼠标捕获和焦点问题