bugsy
bugsy

Reputation: 121

User notification MVVM

I am trying to create a user notification. Ideally a toast-like notification that shows up in the corner for about three seconds.

I am using MVVM-light and I think the notification could be done using its messenger-service.

I have this class:

public class NotificationSync
    {
        public string Messages { get; set; }
    }

In one viewmodel i set up the Messenger like this:

 Messenger.Default.Send(new NotificationSync()
    {
       Messages = "message"
    });

And in my MainviewModel (which is the datacontext of the view) I listen for it like this:

  Messenger.Default.Register<NotificationSync>(this, (action) =>
               Mess = action.Messages );

Mess is a string property on the viewmodel:

   private string mess;
    public string Mess
    {
        get { return mess; }
        set
        {
            mess = value;
            RaisePropertyChanged("Mess");
        }
    }

What I would like to do with mess is to bind it to my view in a toast-like manner. I.E display it for some seconds in my view. Any tips on how to do this? Thank you.

Upvotes: 0

Views: 95

Answers (1)

Berni
Berni

Reputation: 510

What about a Visibility property for your toast plus a timer?

Messenger.Default.Register<NotificationSync>(this, (action) =>
               Mess = action.Messages 
               ShowToast();
);

private void ShowToast()
{
    IsToastVisible = true;
    dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
    dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
    dispatcherTimer.Interval = TimeSpan.FromSeconds(3);
    dispatcherTimer.Start();
}

void OnTimerTick(Object sender, EventArgs args)
{
    IsToastVisible = false;
}

This assumes the textbox to which Mess is bound, is also bound to IsToastVisible and it's using a VisibilityConverter.

Upvotes: 1

Related Questions