Tuesday, June 28, 2011

XAML Namespaces and Root Elements


In XAML file you can specify only one Root element. Root element for XAML file can be Window, Page, ResourceDictionary, Application etc. You can specify various elements inside root element.

<Window x:Class="WpfApplication1.DynamicLookup"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:local="clr-namespace:WpfApplication1"
        Title="DynamicLookup" Height="300" Width="300">
    <Window.Resources>
        <local:Employee x:Key="MyEmployee" />
    </Window.Resources>
    <Grid>
        <Button Background="LightBlue" Content="Click Me!"
                Height="40" Width="150">
        </Button>
    </Grid>
</Window>

In above example Window element is root element. It contains Grid element as child element. You can see xmlns attribute specified with Window element is called as XAML Namespace. You can also specify your own namespace. In above example you can see xmlns:local attribute specified with Window element which represent WpfApplication1 namespace in your xaml file. Using ‘local:’ prefix you can access classes and properties available in WpfApplication1 namespace. In above example i created one instance of an Employee class available in WpfApplication1 namespace.

When you create new WPF application your XAML file loads with two namespaces. One is default namespace use only ‘xmlns’ attribute and another one is ‘xmlns:x’. The ‘x’ prefix is mapped with http://schemas.microsoft.com/winfx/2006/xmal. The x: prefix provides several programming constructs which can be used in XAML file. Here are few examples of x: prefix which are mostly used in XAML file.

x:Key – Used to set unique key for resource in resource dictionary.

<Window.Resources>
  <Style x:Key="MyStyle" TargetType="Button"> 
     <Setter Property="Background" Value="Red" />
  </Style>
</Window.Resources>

x:Name – You can specify name of an element at runtime.  Generally Framework element has Name property but in some cases you might need to use x:Name when framework element level Name property not supported for particular type.

<Button x:Name="MyButton" Content="Click Me!" />

x:Type – This is used to specify attributes which accepts type.

<Window.Resources>
  <Style x:Key="MyStyle" TargetType="{x:Type Button}">
    <Setter Property="Background" Value="Red" />
  </Style>
</Window.Resources>

x:Static – You can refer static members directly in XAML using this prefix.

<TextBlock Text="{x:Static local:Test.MyStatic}" />

No comments:

Post a Comment