我正在写一个自定义控件,并且希望控件在用户单击控件时从编辑状态切换到正常状态。我正在处理LostFocus事件,这有助于当用户退出或者他们点击另一个Focusable控件时。但是如果他们没有点击Focusable,它将不会退出编辑状态。所以我心里有两个解决方案:控件如何处理鼠标在该控件之外的点击?
- 走到树最顶端的元素,当它进入到编辑状态,并添加一个处理
MouseDownEvent
(和处理“处理”事件)。在处理程序中,我会将控制权踢出编辑状态,并从最上面的元素中移除处理程序。这似乎有点破解,但它可能会运行良好。
示例代码:
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);
所以这个工作很完美。我所要做的只是在进入编辑模式时捕捉鼠标,然后当点击它之外时,WPF会自动将焦点从元素上移开。在失去焦点后,我只需要小心ReleaseMouseCapture()。谢谢! – chrislarson
我唯一需要注意的其他事情是,当您按下Windows键或其他应用程序启动时,我将失去鼠标捕捉而不停止我的控件进入编辑状态。所以我不得不处理IsMouseCapturedChanged事件。例如,private void CustomControlIsMouseCapturedChanged(object sender,DependencyPropertyChangedEventArgs e) if((bool)e.NewValue == false) IsEditing = false; } }' – chrislarson