我有一些文本框,我希望焦点的行为与WPF应用程序的正常行为略有不同。基本上,我希望它们的行为更像网页上的文本框。也就是说,如果我单击文本框之外的任何位置,它将失去焦点。最好的方法是什么?
如果答案是以编程方式移除焦点,那么检测边界外的鼠标单击的最佳方法是什么?如果我单击的元素将成为焦点的新接收者,该怎么办?
发布于 2014-01-06 04:55:50
我认为,解决这个问题的更好方法是将MouseDown事件处理程序添加到带有代码的窗口中:
private void window_MouseDown(object sender, MouseButtonEventArgs e)
{
Keyboard.ClearFocus();
}
发布于 2016-04-16 09:19:44
另一种对我有效的方法是使用
Mouse.AddPreviewMouseDownOutsideCapturedElementHandler
例如,假设您有一个TextBlock,当单击它时,应该会通过显示一个有焦点的TextBox而变为可编辑。然后,当用户在TextBox外部单击时,它应该再次被隐藏。下面是你怎么做的:
private void YourTextBlock_OnMouseDown(object sender, MouseButtonEventArgs e)
{
YourTextBox.Visibility = Visibility.Visible;
YourTextBox.Focus();
CaptureMouse();
Mouse.AddPreviewMouseDownOutsideCapturedElementHandler(this, OnMouseDownOutsideElement);
}
private void OnMouseDownOutsideElement(object sender, MouseButtonEventArgs e)
{
Mouse.RemovePreviewMouseDownOutsideCapturedElementHandler(this, OnMouseDownOutsideElement);
ReleaseMouseCapture();
YourTextBox.Visibility = Visibility.Hidden;
}
发布于 2018-06-28 17:00:27
若要避免代码隐藏,可以使用此行为
public class ClearFocusOnClickBehavior : Behavior<FrameworkElement>
{
protected override void OnAttached()
{
AssociatedObject.MouseDown += AssociatedObject_MouseDown;
base.OnAttached();
}
private static void AssociatedObject_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
Keyboard.ClearFocus();
}
protected override void OnDetaching()
{
AssociatedObject.MouseDown -= AssociatedObject_MouseDown;
}
}
在XAML中使用:
在您希望他清除焦点的文本框之外的任何元素上,单击add:
<i:Interaction.Behaviors>
<behaviors:ClearFocusOnClickBehavior/>
</i:Interaction.Behaviors>
https://stackoverflow.com/questions/6489032
复制相似问题