XAML的标记扩展

Tue 09 July 2019 / In categories Library

WinRT, XAML

如果XAML只是使用纯的XML的话,功能并不会非常强大,因为XML适合描述信息以及信息的层次,而不适合描述逻辑。所以XAML加上了一些标记扩展(Markup Extension),来增强其功能。

下面是一个参考自Programming Windows, 6th Edition的例子:

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
    <TextBlock Text="{StaticResource appName}" FontFamily="Portable User Interface" FontSize="48" HorizontalAlignment="Center" VerticalAlignment="Center" />
    <TextBlock Name="topTextBlock" Text="Top Text" HorizontalAlignment="Center" VerticalAlignment="Top">
        <TextBlock.Foreground>
            Yellow
        </TextBlock.Foreground>
    </TextBlock>
    <TextBlock Text="Left Text" HorizontalAlignment="Left" VerticalAlignment="Center" Foreground="{Binding ElementName=topTextBlock, Path=Foreground}" />
    <TextBlock Text="Right Text" HorizontalAlignment="Right" VerticalAlignment="Center" Foreground="{Binding ElementName=topTextBlock, Path=Foreground}" />
    <TextBlock Text="Bottom Text" HorizontalAlignment="Center" VerticalAlignment="Bottom">
        <TextBlock.Foreground>
            <Binding ElementName="topTextBlock" Path="Foreground" />
        </TextBlock.Foreground>
    </TextBlock>
</Grid>

上面的例子中使用到了两个标记扩展:

  • {StaticResource ……}
  • {Binding ……}

通常标记扩展都是在XML属性中使用,但是也可以以XML元素的方式使用,如上面例子中的:

        <TextBlock.Foreground>
            <Binding ElementName="topTextBlock" Path="Foreground" />
        </TextBlock.Foreground>

XAML的标记扩展其实不多(在XAML Overview: Markup extensions可以查看),出了上面出现的两个以外,还有:

  • {x:Bind}
  • {x:Null}
  • {ThemeResource}
  • {TemplateBinding}
  • {RelativeSource}
  • {CustomResource}

(完)

Load Disqus Comments