Add control to grid from code behind in Silverlight
- by Emanuele Bartolesi
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.