WPF には、別のウィンドウ内に (小さい) ウィンドウを開くことができる Popup クラスがあります。これは、Tooltips や ComboBoxes などに使用されます。
現在 WPF ウィンドウ内で開いているこれらのポップアップをすべて見つける必要があるため、それらを閉じることができます。
誰かがまだ必要な場合:
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);
}
これを行う 1 つの方法は、ビジュアル ツリーをナビゲートしてすべてのPopup
オブジェクトを見つけ、開いている場合はそれらを閉じることです。
私のブログには、ビジュアル ツリーをナビゲートする方法の例を提供する VisualTreeHelperがいくつかありますが、すべてのオブジェクトではなく、指定された基準に一致する単一のオブジェクトのみを返すように設定されています。
すべてのオブジェクトを確実に返すようにコードを少し変更する必要があるかもしれませんが、単一のオブジェクトを返すために使用するコードは次のようになります。
/// <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;
}
そして、次のように呼び出すことができます:
var popup = MyVisualTreeHelpers.FindChild<Popup>(MyWindow);