要用popup控件来解决一些问题。就此带来了一批问题。
问题一、 在popup外任意位置点击时要能关闭popup,这个本来简单,只要加上StaysOpen=false就可以了。但我的popup中有个OpenFileDialog控件,点击位于这个控件内,但在popup之外时也会关闭popup。
解决:
在btnOpenFile按钮的PreviewMouseLeftButtonDown事件里添加了
((Popup)((FrameworkElement)this.Parent).Parent).StaysOpen = true;
问题二、 StaysOpen设置为True后,点击按钮变成了这样。popup是TopMost的,挡在了文件窗口前面。
解决:
无法简单解决这个问题,只好采用github上的一个NonTopmostPopup自定义控件取代Popup。
为了在关闭文件选择窗口后popup仍然能够在鼠标点击App任意位置时被关闭,在btnOpenFile按钮的Click事件里添加了
((Popup)((FrameworkElement)this.Parent).Parent).StaysOpen = false;
问题三、上述做法的结果是,如果双击文件名时的鼠标位置在popup区域以外,popup还是会直接关闭。因为双击位置的主窗口控件虽然被文件对话框遮挡,但仍会触发MouseLeftButtonUp(或MouseUp)事件,这可能算是文件对话框的一个bug。我猜是因为双击实际上是在第二次点击的MouseDown事件发生后就生效,对话框就关闭了,再往后还有MouseUp事件,却已经处于没有遮挡的裸奔状态了,当然控件们纷纷响应。
没办法,想workaround吧。我的做法是取消按钮Click事件StaysOpen=false,改在主窗口的MouseLeftButtonDown中加下面的代码遍历控件,遇到popup就设置StaysOpen=false。
private void TheShell_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e) { FindPopupAndClose(TheShell); } // Enumerate all the descendants of the visual object. static public void FindPopupAndClose(Visual myVisual) { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(myVisual); i++) { // Retrieve child visual at specified index value. Visual childVisual = (Visual)VisualTreeHelper.GetChild(myVisual, i); // Do processing of the child visual object. if (childVisual is Popup) ((Popup)childVisual).StaysOpen = false; // Enumerate children of the child visual object. FindPopupAndClose(childVisual); } }
小小的popup这才算整听话了。
原文:http://www.cnblogs.com/dfun/p/5174034.html