Download DropDownMenu.zip - 616.32 KB
Introduction
We know that there is no built in control for menu in Silverlight 2.Here a silverlight DropDownMenu is created using silverlight popup control and button.
I'm happy to present my first article on CodeProject.I'm hoping to use the experience to improve my writing style. So your comments, suggestions and criticism are very welcome.
Background
Here firstlevel menuitems are buttons.When a button is clicked then a popupcontrol is opened which contains submenu items.
Using the code
First Here a popup control is declared .When an individual button is clicked then a popup control is opened using the following code.
private Popup _popUp;
public Popup PopUp
{
get { return _popUp; }
set { _popUp = value; }
}
private void menuItem_Selected(object sender, MouseButtonEventArgs e)
{
if (this.PopUp.Child != null)
{
this.PopUp.Child = null;
this.PopUp.IsOpen = false;
}
Button visual = sender as Button;
GeneralTransform transform = base.TransformToVisual(visual);
Point point = transform.Transform(new Point(0.0, 0.0));
StackPanel sp = new StackPanel();
sp.Children.Clear();
SubMenu oItem = new SubMenu(_popUp);
oItem.fillDetails("Setu");
sp.Children.Add(oItem);
oItem = new SubMenu(_popUp);
oItem.fillDetails("Asif");
sp.Children.Add(oItem);
oItem = new SubMenu(_popUp);
oItem.fillDetails(" Know about bangladeshi people ");
sp.Children.Add(oItem);
this._popUp.Child = sp;
_popUp.Child.MouseLeftButtonDown += new MouseButtonEventHandler(Child_MouseLeftButtonDown);
this._popUp.VerticalOffset = this.Margin.Top + Math.Abs(point.Y) + visual.ActualHeight - 2;
this._popUp.HorizontalOffset = this.Margin.Left + Math.Abs(point.X);
this._popUp.IsOpen = true;
}
Here another issue is communication between Popup
control and Silverlight main application Form. The commutation is done using
MouseLeftButtonDown.
_popUp.Child.MouseLeftButtonDown += new MouseButtonEventHandler(Child_MouseLeftButtonDown);
Another thing is to determine which menuitem is clicked.Here
each menuitem is created using a rectangle and textblock wrapped with a GRID.For
that the following code is used:
public event EventHandler menucommand;
void Child_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.Source is TextBlock)
{
string str = ((TextBlock)e.Source).Text;
if (menucommand != null)
{
menucommand(str, null);
}
}
else if (e.Source is Rectangle)
{
string str = string.Empty;
foreach (FrameworkElement em in ((Grid)((Rectangle)e.Source).Parent).Children)
{
if (em is TextBlock)
{
str = ((TextBlock)em).Text;
}
}
if (menucommand != null)
{
menucommand(str, null);
}
}
PopUp.IsOpen = false;
}
Reference
Thanks to Jose Fajardo for his blog.
http://advertboy.wordpress.com/2008/04/13/my-digg-mashup-that-taught-me-so-much-about-silverlight-20-beta-part-1/
History