Accessing Objects and Their Properties

XAML objects can be accessed from C# code easily because there is a direct relationship between a C# classe and a XAML object as well as the attributes of the former and properties of the latter.

The C Sharp code

When you create an XAML item with Expression Blend, it generates a C# file associated with this item. To see it, click on the icon to the left of the XAML filename:

To access the C Sharp code, it is necessary to have installed Visual Studio Express. You can then click on Windows1.xaml.cs to enter the code editor.
A namespace is there which is the name of the project, it is the space of your application. It also contains a class of Window type, it is the main Windows of your application.

Events managers

These are functions that are assigned by name at predefined events of XAML. Click for example, it assigns "clicme" which is the name of a function to be executed when the event occurs, in other words when the user clicks the mouse button.
The event managers have predefined arguments:
- Sender, the name of the object to which the event is associated, for example, the button on wich the mouse is clicked.
- Args, a parameter which depends on the class of the event.

Accessing the inner components

To access the parts of an object, we use their names directly, in contrast to what happens with Silverlight.

x:Name

Example:

<Window Click="clicButton">
    <Button x:Name="clicme" />
</Window>

The C# function:

void clicButton(object sender,  EventArgs args)
{
  object x = clicme;
}

Accessing an object and its properties

The Expression Blend editor generates a default Grid container. We replace it with Canvas to remove constraints of placement.

If you want to access an XAML object's property, give the name of the object combinedt with the name of the property:

<Canvas x:Name="LayoutRoot" Width="400">
    <Button x:Name="clicme" Width="128" Height="20" Canvas.Left="24" Canvas.Top="20"
           Content="Click me" Click="clicButton" />   
   <TextBlock x:Name="disp"  Height = "20"
		Width = "128" Background="#FF4ED2D5" Text="Nothing" Canvas.Left="24" Canvas.Top="50" />
 </Canvas>

and the function:

private void clicButton(object sender, EventArgs e)
{
            disp.Text =  "Thanks";
            clicme.Content = "Click again";
}

We see that the property Content is associated directly to the name of the button, "clicme", and the Text property is associated with the name of the block of text "disp" and the function may change what the program display by assigning something to these properties.
In the example, when you click on the button, the text field containing "Nothing" now contains "Thank you", and also the button is changed, it displayed "Click me", it now shows "Click again".

Source code

(c) 2008 Denis Sureau. Scriptol.com