如何检查 WPF 控件是否托管在 WinForms 中?

How to check if WPF control is hosted within WinForms?

我有一个 WPF 控件,在某些情况下它作为 WPF 应用程序的一个组件存在,而在其他情况下托管在 Windows 表单中。如何检测第二种情况(WinForms 中嵌入了一个 WPF 控件)?

试试这个:

HwndSource wpfHandle = PresentationSource.FromVisual(this) as HwndSource;
if (wpfHandle != null)
{
    ElementHost host = System.Windows.Forms.Control.FromChildHandle(wpfHandle.Handle) as ElementHost;
    if(host != null)
    {
        //hosted in ElementHost...
    }
}