Dec 05

With thanks to Jan Van Der Haegen for his ExtensionsMadeEasy, without which I could not have achieved this. Winking smile

Basically, in Lightswitch, I wanted a button on the Ribbon that allows the user to view messages. The Button should update itself to reflect how many unread messages are available, like so:

image

First install Jan’s Extensions, which you can get here.

Then add the following code to the application.cs. This creates an event you can raise when a new message becomes available.

public partial class Application
{
    public delegate void NewMessage();
    public event NewMessage MessageReceived;

    public void RaiseMessageReceived()
    {
        if (this.Details.Dispatcher.CheckAccess())
            MessageReceived();
        else
            this.Details.Dispatcher.BeginInvoke(delegate()
            {
                MessageReceived();
            });
    }
}

Then you need the following code, which creates the command:

public class MessagesCommand : ExtensionsMadeEasy.ClientAPI.Commands.EasyCommandExporter
    {
        private int messageCount = 0;
        public int MessageCount
        {
            get { return messageCount; }
            set { messageCount = value; }
        }

        public new string Description
        {
            get { return string.Format("You have {0} message(s) waiting to be read", MessageCount); }
        }

        public new string DisplayName
        {
            get { return string.Format("Messages ({0})", MessageCount); }
        }

        public MessagesCommand() :
            base("", "", "Screens",
            new Uri(@"/ECSManager.Client;component/Resources/mail-128.png", UriKind.Relative))
        {
            base.Description = this.Description;
            base.DisplayName = this.DisplayName;
            Application.Current.MessageReceived += new Application.NewMessage(Current_MessageReceived);
        }

        void Current_MessageReceived()
        {
            // MessageReceived event is raised on the application's thread
            // so need to do the UI update on a different thread
            MessageCount++;
            Microsoft.LightSwitch.Threading.Dispatchers.Main.BeginInvoke(() =>
                {
                    base.DisplayName = this.DisplayName;
                    base.Description = this.Description;
                });
        }

        public override void Execute(Microsoft.LightSwitch.Client.IScreenObject currentScreen)
        {
            // Open the Messages Screen (put your code here)
        }
    }

Scribbles Out.

Tags:
blog comments powered by Disqus