By default, your Visual Studio project includes a code file, sometimes called a code-behind file. The code file contains one of the managed languages supported by Silverlight through the common language runtime (CLR), such as C# or Visual Basic. For more information on the CLR and Silverlight, see Common Language Runtime Overview.
The code-behind file name takes Page.xaml and appends the language type (for example, Page.xaml.cs). The code-behind file is where you can apply logic to your XAML objects. You can create UI objects in code and add them to your visible element tree. In addition, classes created in your code-behind file (and in any code file included in your project) can be accessed from XAML. For example, you can define your own controls and then create instances of them in XAML. For more information, see XAML Namescopes (Silverlight 2) and XAML and Mapping Custom XML Namespace Values (Silverlight 2).
The following example adds a Click event handler that will change the color of the rectangle to blue.
In XAML, add the Click event to the Button and an x:Name attribute to the Rectangle. The x:Name allows you to reference the rectangle in the code-behind file.
|
<Button Height="25" Width="100" Grid.Column="0" Grid.Row="0" Click="Button_Click"/>
<Rectangle x:Name="rect1" Fill="Red" Width="150" Height="100" Grid.Column="1" Grid.Row="1"/>
|
In the code-behind file, define the Click event handler. For more information on using events, see Events Overview (Silverlight 2).
|
private void Button_Click(object sender, RoutedEventArgs e)
{
rect1.Fill = new SolidColorBrush(Colors.Blue);
}
|
The following illustration shows how this code renders.
.png)
Run this sample