Thursday 19 June 2008

MessageBox.Show in Silverlight

Well, it's kind of obvious to anyone that has done any browser based Javascript development, but thought this was worth posting for those of you that do a lot of Windows Development and are wondering how to show a MessageBox in Silverlight. For those of you that have tried it:

MessageBox.Show("Hello world!");

OOPS! Compiler error... that doesn't work, Silverlight does not have a MessageBox class like WPF / WinForms / Win32. Instead, you can ask the browser to do this for you. How do you do this you might ask?

HtmlWindow.Alert("Hello world!");

This is the exact equivalent of the javascript alert function, which would look something like this:

alert("Hello world!");

So what if you want more control? Well, you will find the browser does not provide quite as much as desktop apps for this. In WPF, you can control the message, the title, the icon, the colours, buttons and more! Alert() will simply display a normal dialog with an OK button and the message, and a browser dependent title. The other option the browser gives you is to display a message box with "OK" and "Cancel" options and to be able to read the result of what the user chooses. In WPF you would do:

DialogResult result = MessageBox.Show("Shall I proceed?", "Title", MessageBoxButtons.OKCancel);
if (result == MessageBoxResult.OK)
{
  // process the OK
}

In Silverlight, the equivalent is:

bool result = HtmlPage.Window.Confirm("Shall I proceed?");
if (result)
{
  // process the OK
}

3 comments:

Anonymous said...

Hey Neil, I have been wondering about your Command implementation for Silverlight. Send me e-mail and let's discuss...I think it can be simplified. I am John dot Gossman at Microsoft dot com

Vikram Pendse said...

I guess statement :
bool result = HtmlPage.Window.Confirm("Shall I proceed?");
if (result)
{...

can be just simplified to
if(HtmlPage.Window.Confirm("Shall I proceed?"))
{
//Logic
}

I personally don't think we need to have another variable here :)

Vikram Pendse
Microsoft MVP
http://pendsevikram.blogspot.com

Unknown said...

how do you use messagebox.show() in a silverlight vb app?