Add control to grid from code behind in Silverlight
Posted
by Emanuele Bartolesi
on Geeks with Blogs
See other posts from Geeks with Blogs
or by Emanuele Bartolesi
Published on Wed, 23 Nov 2011 23:42:40 GMT
Indexed on
2011/11/24
1:53 UTC
Read the original article
Hit count: 285
In this post I show how you can easily add a control to a silverlight grid layout from code behind.
First you draw the grid in the xaml.
<Grid x:Name="LayoutRoot" Background="Red"> <Grid.RowDefinitions> <RowDefinition Height="20"> </RowDefinition> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="300"> </ColumnDefinition> </Grid.ColumnDefinitions> </Grid>
Now in the page constructor add the following code.
public MainPage() { InitializeComponent(); var myButton = new Button { Name = "btnOk", Content = "Ok", }; myButton.SetValue(Grid.RowProperty, 1); myButton.SetValue(Grid.ColumnProperty, 1); myButton.Click += myButton_Click; LayoutRoot.Children.Add(myButton); }
Also add the evento of the button.
void myButton_Click(object sender, RoutedEventArgs e) { }
The code needs no comment because it’s very simple.
The only important thing is the method SetValue because it is used to set XAML attribute of element.
For a better understanding I have created an example that you can download from here.
© Geeks with Blogs or respective owner