C# wpf鼠标捕获和焦点问题
我在UserControl中有一个文本框。 UserCopControl具有字符串类型的依赖项属性“Text”。 usercontrol的文本属性绑定到TextBox文本属性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),
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");
}