Search code examples
c#wpfxamlmvvmnotifyicon

WPF accessing code-behind from view models


Using the NotifyIcon project to show balloons in my c# app.

I want a trigger from the program to be displayed as a popup/balloon when it occurs. The problem is that I can only see how to show a balloon using the .ShowCustomBalloon method in code-behind of the .xaml.cs file, which doesn't have context in my ViewModel. The examples in the project work because they use code-behind to show the balloon contents.

What I need is a way to have an event listener on the .xaml file that can trigger this show balloon, that is bound to a property of the viewModel. Problem is my experience in c# app dev. is not great and I am wondering how to go about this.


Solution

  • In code-behind (the View) you should subscribe for property changed event (or some other event, it really depends on your ViewModel implementation).

    Here is sample ViewModel:

    public class SomeViewModel : INotifyPropertyChanged
    {
      public event PropertyChangedEventHandler PropertyChanged;
    
      private string someProperty;
      public string SomeProperty
      {
          get { return someProperty; }
          set
          {
            someProperty = value;
            OnPropertyChanged();
          }
      }
    
      protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
      {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
      }
    }
    

    Here is sample View:

    public partial class SomeView : Window
    {
        public DiscImageView()
        {
            //  ...
    
            viewModel.PropertyChanged += ViewModel_PropertyChanged;
        }
    
        private void ViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(SomeViewModel.SomeProperty))
            {
                //  Logic for changed property event
            }
        }
    }
    

    Also consider using of some MVVM library or framework, they simplify life a lot. I suggest MVVMLight, besides other it has messaging capabilities.