我正在编写一个自定义控件,想让控件在用户点击控件之外的区域时从编辑状态切换到正常状态。我正在处理LostFocus事件,这有助于当用户切换到另一个可聚焦的控件时或者按Tab键离开控件时。但如果他们没有点击其他可聚焦的东西,它不会退出编辑状态。因此我有两个解决方案:
- 在进入编辑状态时向上遍历树形结构到最顶层元素,并添加
MouseDownEvent
处理程序(并处理"handled"事件)。在处理程序中,我将把控件从编辑状态中移除,并从最顶层元素中删除处理程序。这似乎有点像hack,但可能效果很好。
示例代码:
private void RegisterTopMostParentMouseClickEvent()
{
_topMostParent = this.FindLastVisualAncestor<FrameworkElement>();
if ( _topMostParent == null )
return;
_topMostParent.AddHandler( Mouse.MouseDownEvent, new MouseButtonEventHandler( CustomControlMouseDownEvent ), true );
}
private void UnRegisterTopMostParentMouseClickEvent()
{
if ( _topMostParent == null )
return;
_topMostParent.RemoveHandler( Mouse.MouseDownEvent, new MouseButtonEventHandler( CustomControlMouseDownEvent ) );
_topMostParent = null;
}
- 使用
Mouse.PreviewMouseDownOutsideCapturedElement
并在我的控件上添加处理程序。 在处理程序中,我会将控件退出其编辑状态。 但是我似乎无法使事件触发。 Mouse.PreviewMouseDownOutsideCapturedElement何时启动?
示例代码:
AddHandler( Mouse.PreviewMouseDownOutsideCapturedElementEvent, new MouseButtonEventHandler( EditableTextBlockPreviewMouseDownOutsideCapturedElementEvent ), true );