'Object reference not set to an instance of an object' 最小化时在用户控件中调用 window 的方法?

'Object reference not set to an instance of an object' When calling window's method in usercontrol when minizing?

我有一个balloon tool tip that act as taskbar notifier。 该工具提示是用户控件 class。 我的情况是:我有一个 window,上面有一些点击方法和工具提示。 场景就像在我的 window 倒数计时器方法中 'X' 时间后,工具提示将弹出以使用 yes/no 按钮提醒(你还在处理它吗?像那样)

当我尝试在用户控件 class 中调用 window 的方法时,使用这段代码是正常的

//inside tooltip user control class
 System.Windows.Application.Current.Windows.OfType<My_Window>().SingleOrDefault(x => x.IsActive).My_Window_Method();

但是,当我最小化 windows 或单击 window 未突出显示的任何内容时,应用程序会提示 'Object reference not set to an instance of an object' 并指向上面的相同代码。

//inside tolltip usercontrol class ( same code as above)
 private void Yes_Click(object sender, RoutedEventArgs e)
    {

        System.Windows.Application.Current.Windows.OfType<My_Window>().SingleOrDefault(x => x.IsActive).My_Window_Method();
        TaskbarIcon taskbarIcon = TaskbarIcon.GetParentTaskbarIcon(this);

        taskbarIcon.CloseBalloon();
    }

所以我的问题是:当最小化应用程序或应用程序未突出显示时,是否有一种解决方案可以在用户控件 class 中安全地调用 window 的方法?谢谢

当您最小化或将焦点设置为其他任何内容时,isactive 变为 false,因为 window 不再具有焦点。

https://docs.microsoft.com/en-us/dotnet/api/system.windows.window.isactive?view=netframework-4.7.2

如果没有任何条件,Singleordefault 将 return 为 null。

因此我建议您删除 isactive 检查。

System.Windows.Application.Current.Windows.OfType<My_Window>().SingleOrDefault).My_Window_Method();

但我也建议您考虑解耦并使用诸如 mvvmlight messenger 之类的发布子模式。