Dynamically creating controls in Silverlight is a breeze.
I am using Visual Studio 2010 Release Candidate.
I am starting a Silverlight Application Project.
I am selecting Asp .Net Web Project as new Web Project Typer.
As mentioned in the previous blog VS 2010 comes with excellent tool support for Silverlight.
I am adding a Stack Panel (stp1)to hold the dynamically created controls and a TextBlock to display the message based on the control selected.
Going to the load event of Main Page I am dynamically creating Buttons.
List<string> lstr = new List<string> { "Shalvin", "Praseed Pai" };
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
Button btn;
foreach (string str in lstr)
{
btn = new Button();
btn.Content = str;
btn.Tag = str;
btn.Click += new RoutedEventHandler(btn_Click);
stp1.Children.Add(btn);
}
}
Notice I have only one event Handler for the whole set of controls.
I am going to have different functionlity for different buttons by identifying the tag property of Button.
private void btn_Click(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
string txtTag = btn.Tag.ToString();
tblMessage.Text = txtTag;
}
Showing posts with label Dynamically Adding Controls. Show all posts
Showing posts with label Dynamically Adding Controls. Show all posts
Monday, March 22, 2010
Silverlight Dynamically Creating Controls and Attaching Event Handlers
Labels:
Dynamically Adding Controls,
Shalvin,
silverlight
Subscribe to:
Posts (Atom)