Search code examples
c#wpftaskbar

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


I have a balloon tool tip that act as taskbar notifier. That tool tip is a user control class. My case is: i have a window that have some clicks methods and a tooltip above. The scenario is like after 'X' time in my countdown timer method in my window, the tool tip will pop up to remind with yes/no buttons ( are u still working on it? like that)

When i try to call a window's methods inside a user control class, its normal with this code

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

But when i minimize the windows or click anything that the window is not highlighted, the app tells that 'Object reference not set to an instance of an object' and pointed at the same code above.

//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();
    }

So my question is : is there a solution to safely call a window 's method inside a usercontroll class when minize the app or the app is not highlighted? thanks


Solution

  • When you minimise or set focus to anything else then isactive becomes false, because the window no longer has focus.

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

    Singleordefault will return null if nothing qualifies.

    Hence I suggest you remove the isactive check.

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

    But I also suggest you consider decoupling and using a pub sub pattern such as mvvmlight messenger.