About Me

My photo
is a software engineer from bangalore.

Blog Archive

Tuesday, March 17, 2009

Using delegates and Events in Silverlight

Using Delegates and Events in Silverlight follows the same procedure as in a windows or web program.

The scenario in which we use a delegate is also the same in silverlight. The Scenario is We have a UserControl
A inside an other page or user control B, and we need an event to control the actions of A from B.

Our aim here is to add a mouse click event to the UserControl
A
In this case, inside
A we declare a delegate as shown below.

public delegate void UserControlClicked(object sender, MouseButtonEventArgs e);


We Now declare an event for this particular delegate. It is this event that we call to invoke the method.

public event UserControlClicked RectangleClicked;

Now we write in the LeftButtonDown event of the UserControl
A,

private void UserControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (
RectangleClicked!= null)
{
RectangleClicked(sender, e);
}
}


We check for the event condition to be null, just to verify that the event is called at
B.

Now at
B,

Rectangle b = new Rectangle();
b.
RectangleClicked+= new Rectangle.userControlClicked(b_RectangleClicked );


and in the method
RectangleClicked,


void b_RectangleClicked(object sender, MouseButtonEventArgs e)
{
FrameworkElement element = sender as FrameworkElement;
Rectangle box = (Rectangle)element;
string detail= "\Height: " + box.Height + " Width: " + box.Width + " Name: " + box.Name
HtmlPage.Window.Alert("Rectangle box "+detail);

}



For these to work, you must include the following namespaces.
using System.Windows.Browser; // to display the alert box.

Any mistakes in the post, please do add a comment.

Thank you.

1 comment: