WPF has the Popup class with which you can open a (small) window inside another window. This is used for example for Tooltips or ComboBoxes.
I need to find all of these popups which are currently opened inside a WPF window, so I can close them.
WPF has the Popup class with which you can open a (small) window inside another window. This is used for example for Tooltips or ComboBoxes.
I need to find all of these popups which are currently opened inside a WPF window, so I can close them.
If someone still need:
public static IEnumerable<Popup> GetOpenPopups()
{
return PresentationSource.CurrentSources.OfType<HwndSource>()
.Select(h => h.RootVisual)
.OfType<FrameworkElement>()
.Select(f => f.Parent)
.OfType<Popup>()
.Where(p => p.IsOpen);
}
One way of doing this would be to navigate the Visual Tree to find all Popup
objects, and close them if they're open
I have some VisualTreeHelpers on my blog that provide an example of how you can navigate the Visual Tree, although they are setup to only return a single object that matches the specified criteria, and not all objects.
You'll probably need to modify the code a bit to make sure it returns all objects, but the code I use for returning a single object looks like this:
/// <summary>
/// Looks for a child control within a parent by type
/// </summary>
public static T FindChild<T>(DependencyObject parent)
where T : DependencyObject
{
// Confirm parent is valid.
if (parent == null) return null;
T foundChild = null;
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
// If the child is not of the request child type child
T childType = child as T;
if (childType == null)
{
// recursively drill down the tree
foundChild = FindChild<T>(child);
// If the child is found, break so we do not overwrite the found child.
if (foundChild != null) break;
}
else
{
// child element found.
foundChild = (T)child;
break;
}
}
return foundChild;
}
And can be called like this:
var popup = MyVisualTreeHelpers.FindChild<Popup>(MyWindow);