Chuyển đến nội dung

Bài 9 · XAML and Layouts

Namespaces and Markup Extensions

Learn XAML namespaces (xmlns, clr-namespace), the x: language features, and markup extensions such as StaticResource, DynamicResource, Binding, x:Static, x:Type, x:Null and OnPlatform.

Two pieces of XAML syntax look strange at first: the xmlns lines at the top of every file, and values in curly braces like {Binding Name} or {StaticResource Primary}. The first tells XAML where to find classes. The second, called markup extensions, lets an attribute compute its value instead of being a fixed string. This lesson explains both, and shows how a markup extension is parsed.

MAUI XAML is read-only here. The runnable block is a labelled stand-in that parses markup-extension text and resolves resources; the real parser is part of MAUI.

XML namespaces

XML
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:models="clr-namespace:HelloApp.Models"
             xmlns:vm="clr-namespace:HelloApp.ViewModels"
             x:Class="HelloApp.Views.OrderPage"
             x:DataType="vm:OrderViewModel">
  • The default namespace (no prefix) holds all MAUI controls: Label, Grid, Button and so on.
  • x: is the XAML language namespace: x:Class, x:Name, x:Key, x:DataType, x:Static, x:Type, x:Null, x:Array, x:Arguments.
  • clr-namespace: prefixes point at your own C# namespaces. After declaring xmlns:models="clr-namespace:HelloApp.Models" you can write <models:Product />. If the class is in another assembly add ;assembly=Name.
  • The using form is a shorter alternative in recent versions: xmlns:models="using:HelloApp.Models".

The prefix name is your choice (vm, models, local); it is only a label for the namespace. If you see "type not found" errors, check the namespace, the spelling and whether the class is public.

What is a markup extension?

A markup extension is a class that returns a value for a property. You write it in curly braces:

XML
<Label Text="{Binding Title}"
       TextColor="{StaticResource Primary}"
       FontFamily="{DynamicResource BodyFont}" />

The text inside the braces starts with the extension name (Binding, StaticResource; the Extension suffix is optional), followed by arguments. Arguments can be positional ({StaticResource Primary} is the same as {StaticResource Key=Primary}) or named and separated by commas ({Binding Name, Mode=TwoWay}).

The built-in markup extensions

Extension Purpose
{StaticResource Key} Look up a resource once, when the XAML loads
{DynamicResource Key} Look up a resource and update if it changes later (themes)
{Binding Path} Connect a property to a source property (see data binding)
{TemplateBinding Path} Bind inside a control template to the templated control
{x:Static local:Constants.Title} Read a static field, property or constant
{x:Type vm:MainViewModel} Get a Type object
{x:Null} The value null
{x:Reference Name} Refer to another named element in the same page
{OnPlatform ...} / {OnIdiom ...} Pick a value by platform or device type
{AppThemeBinding Light=..., Dark=...} Pick a value by system theme
XML
<Label Text="{x:Static local:Constants.AppName}" />

<Button Text="Delete"
        IsEnabled="{Binding Source={x:Reference ItemsList}, Path=SelectedItem, Converter={StaticResource IsNotNull}}" />

<BoxView Color="{AppThemeBinding Light=White, Dark=#222222}" />

<Label Text="Running on"
       FontSize="{OnPlatform Android=16, iOS=17, WinUI=15, Default=14}" />

is quicker and is used for values that never change; is needed when the resource can be replaced while the app runs, for example a theme switch. A StaticResource that refers to a key defined later in the same file fails; define resources before they are used.

OnPlatform and OnIdiom

OnPlatform selects a value per operating system. Platform names in XAML are Android, iOS, MacCatalyst, WinUI and Default. OnIdiom selects per device type: Phone, Tablet, Desktop, Watch, TV.

XML
<Grid Padding="{OnIdiom Phone='10', Tablet='30', Desktop='40'}">

Quote the values when they contain commas, such as thickness values ('10,20').

Where resources come from

StaticResource and DynamicResource look for the key in this order: the element's own Resources, then its parent's, up the tree through the page, and finally App.xaml's Resources. A global colour goes in App.xaml; one used on a single page goes in ContentPage.Resources:

XML
<ContentPage.Resources>
    <Color x:Key="Accent">#512BD4</Color>
    <x:Double x:Key="CardRadius">12</x:Double>
    <x:String x:Key="Welcome">Welcome back</x:String>
</ContentPage.Resources>

x:Key names the resource. The XAML types x:String, x:Double, x:Int32, x:Boolean let you define simple values. Styling and resources are covered in their own chapter.

How markup extensions are parsed, runnable

A markup extension is only text until the XAML parser reads it. The stand-in below parses {Name Arg, Key=Value} text and then resolves StaticResource and x:Static-like values from dictionaries. It is much simpler than MAUI's parser, but it shows the exact structure of the syntax: the name, positional arguments and named arguments.

C# Stand-in: parse and resolve markup extensions

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

A missing resource key is a very common run-time crash in real apps: MAUI throws an XamlParseException ("StaticResource not found for key Missing"). The stand-in reports the same problem as text.

Defining your own markup extension

You can write one with IMarkupExtension<T> (read-only):

C#
[ContentProperty(nameof(Key))]
public class TextExtension : IMarkupExtension<string>
{
    public string Key { get; set; } = "";

    public string ProvideValue(IServiceProvider serviceProvider) =>
        Strings.ResourceManager.GetString(Key) ?? $"[{Key}]";

    object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider) =>
        ProvideValue(serviceProvider);
}
XML
<Label Text="{local:Text Key=Welcome}" />

This is a standard way to make localisation simple.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What is the main difference between StaticResource and DynamicResource?

    DynamicResource keeps watching the key (useful for themes); StaticResource reads the value once.
  2. 2. What does xmlns:vm="clr-namespace:HelloApp.ViewModels" do?

    It maps a prefix to a CLR namespace so XAML can refer to your own types.
  3. 3. Which value gives null in XAML?

    {x:Null} is the markup extension that returns null.
  4. 4. Which markup extension picks a value by operating system?

    OnPlatform chooses per platform (Android, iOS, MacCatalyst, WinUI, Default).

Summary

  • xmlns maps prefixes to namespaces; x: provides language features; clr-namespace reaches your own types.
  • Markup extensions in {} compute property values: resources, bindings, statics, platform values, theme values.
  • Resources are looked up from the element up to App.xaml; a missing key throws at run time.
  • You can write your own markup extension with IMarkupExtension<T>.

Next: Common Controls

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.