It is better to step in code and see the simplest XAML code
in action. Listing 1 provides a sample application that lets you to put a text
in a TextBox then click on a Button. Listing 2, which is the handler code for
this click, does the rest and shows your text in a MessageBox. The output is
provided in Figure 1.
Listing 1
<Window x:Class="IntroductionToXAML.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Introduction To XAML" Height="200" Width="300"
>
<StackPanel>
<TextBox Name="MyTextBox"
Width="200"
Height="30"
Margin="40" />
<Button Click="ButtonClickHandler"
Width="60"
Height="20">
Click me!
</Button>
</StackPanel>
</Window>
Listing 2
void ButtonClickHandler(object sender, RoutedEventArgs e)
{
MessageBox.Show(string.Format
("You typed '{0}' in TextBox!", MyTextBox.Text), "XAML");
}
Figure 1
Initially you can find some points from this simple code.
1.
XAML file starts with a <Window /> element as root. This element
will be the most common root element for your XAML files.
2.
Default namespace for XAML file is "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
and it has another "x" namespace which is set to "http://schemas.microsoft.com/winfx/2006/xaml."
3.
Main elements are embedded in a <StackPanel /> element. StackPanel
is one of the XAML elements for laying out other elements.
4.
There is no identifier for my Button. In XAML you do not need to put a
name as identifier for your controls unless you want to refer to them from
other parts of your code. This helps you to have shorter codes. But as I want
to refer to my TextBox in my code, I defined a Name attribute for it and set it
to MyTextBox.
5.
My Button has a Click attribute which is set to an event handler in my
code to handle the Click event of this button.
Note that I could merge Listing 1 and Listing 2 codes in one
XAML file and use inline model to write my click event as you see in Listing 3.
Listing 3
<Window x:Class="IntroductionToXAML.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Introduction To XAML" Height="200" Width="300"
>
<StackPanel>
<TextBox Name="MyTextBox"
Width="200"
Height="30"
Margin="40" />
<Button Click="ButtonClickHandler"
Width="60"
Height="20">
Click me!
</Button>
</StackPanel>
<x:Code>
<![CDATA[
void ButtonClickHandler(object sender, RoutedEventArgs e)
{
MessageBox.Show(string.Format
("You typed '{0}' in TextBox!", MyTextBox.Text), "XAML");
}
]]>
</x:Code>
</Window>
Note that <x:Code /> element must be a direct child of
root element in a XAML file. Since you do not have great tools, such as
Intellisense in inline model, and your code will be long and hard to read in
this case, I do not recommend using inline model.