我在用户控件中有一个文本框。Usercopntrol 有一个字符串类型的依赖属性“文本”。用户控件的 Text 属性绑定到 TextBoxes Text 属性。
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
"Text",
typeof(String),
typeof(MyTextControl),
new FrameworkPropertyMetadata(String.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
xml代码...
<TextBox
x:Name="textbox1"
Text="{Binding ElementName=MyTextControl, Path=Text, UpdateSourceTrigger=LostFocus}"
...
</TextBox>
请注意,我们的应用程序中有理由认为 UpdateSourceTrigger 是 LostFocus 而不是 PropertyChanged,以提供“撤消”功能。当焦点丢失时,文本更改将创建一个撤消步骤。
现在有一种情况是用户在用户控件之外单击应用程序内的另一个控件。然后 wpf 系统不会触发“FocusLost”事件。因此,我使用
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 事件?