Search code examples
c#wpfmvvmnotifyicon

WPF NotifyIcon not firing MouseEnter event (How to update NotifyIcon viewmodel when tooltip is displayed)


I'm utilizing the WPF NotifyIcon library for displaying tray icon and tooltip when user hover's mouse over the tray icon. I defined my Tooltip as UserControl:

<tb:TaskbarIcon  x:Class="MyAwesomeApp.TrayIconUserControl">
    <tb:TaskbarIcon.TrayToolTip>
       <Grid>
          <TextBlock Text="{Binding TextFromViewModel}" />
       </Grid>
    </tb:TaskbarIcon.TrayToolTip>
</tb:TaskbarIcon>

And I'm creating it in main ViewModel:

private TaskbarIcon TrayIcon;

public void CreateTrayIcon()
{
  TrayIcon = new TrayIconUserControl();
}

However, I want to update the taksbar's viewmodel when user will hover over the tray icon (just when tooltip is actually displayed). How to achieve that? None of the TrayIcon's events, as MouseEnter, TooltipDisplayed etc are firing, so ViewModel will read it's values only when initiated.


Solution

  • Should be as easy as calling the PreviewTrayToolTipOpen event, either in your XAML:

    <tb:TaskbarIcon  x:Class="MyAwesomeApp.TrayIconUserControl"
                     PreviewTrayToolTipOpen="PreviewTrayToolTipOpen">
        <tb:TaskbarIcon.TrayToolTip>
           <Grid>
              <TextBlock Text="{Binding TextFromViewModel}" />
           </Grid>
        </tb:TaskbarIcon.TrayToolTip>
    </tb:TaskbarIcon>
    

    Or in you codebehind:

    TrayIcon = new TrayIconUserControl();
    TrayIcon.PreviewTrayToolTipOpen += PreviewTrayToolTipOpen;
    

    And the two methods have the same handler signature:

        private void PreviewTrayToolTipOpen(object sender, RoutedEventArgs routedEventArgs)
        {
            throw new NotImplementedException();
        }
    

    Hope this helps