Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# wpf鼠标捕获和焦点问题_C#_Wpf_Keyboard Events_Lost Focus - Fatal编程技术网

C# wpf鼠标捕获和焦点问题

C# wpf鼠标捕获和焦点问题,c#,wpf,keyboard-events,lost-focus,C#,Wpf,Keyboard Events,Lost Focus,我在UserControl中有一个文本框。 UserCopControl具有字符串类型的依赖项属性“Text”。 usercontrol的文本属性绑定到TextBox文本属性 public static readonly DependencyProperty TextProperty = DependencyProperty.Register( "Text", typeof(String), typeof(MyTextControl),

我在UserControl中有一个文本框。 UserCopControl具有字符串类型的依赖项属性“Text”。 usercontrol的文本属性绑定到TextBox文本属性

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

<TextBox
            x:Name="textbox1"
            Text="{Binding ElementName=MyTextControl, Path=Text, UpdateSourceTrigger=LostFocus}"
            ...
</TextBox>
在这种情况下,这对更新非常有用

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

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

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