Welcome

首页 / 软件开发 / .NET编程技术 / WPF学习笔记 - 4. XAML

WPF学习笔记 - 4. XAML2010-10-11 rainsts.net Q.yuhenMicrosoft 将 XAML 定义为 "简单"、"通用"、"声明式" 的 "编程语言"。这意味着我们会在更多的地方看到它(比如 Silverlight),而且它显然比其原始版本 XML (XAML 是一种基于 XML 且遵循 XML 结构规则的语言) 多了更多的逻辑处理手段。如果愿意的话,我们完全可以抛开 XAML 来编写 WPF 程序。只不过这有点类似用记事本开发 .NET 程序的意味,好玩不好用。XAML 的定义模式使得非编程人员可以用 "易懂" 的方式来刻画 UI,并且这种方式我们早已熟悉,比如 WebForm,亦或者是我一直念念不忘的 Delphi Form (偶尔想起而已,其实早将 Object Pascal 忘得精光了)。

<Window x:Class="Learn.WPF.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1">
<Grid>
</Grid>
</Window>

这是一个非常简单的 XAML,它定义了一个空白 WPF 窗体(Window)。XAML 对应于 .NET 代码,只不过这个过程由特定的 XAML 编译器和运行时解释器完成。当解释器处理上面这段代码时,相当于:

new Window1 { Title = "Window1" };

从这里我们可以体会两者的区别,用 XAML 的好处是可以在设计阶段就能看到最终的展现效果,很显然这是美工所需要的。你可以从 VS 命令行输入 "xamlpad.exe",这样你会看到直观的效果。

作为一种应用于 .NET 平台的 "语言",XAML 同样支持很多我们所熟悉也是必须的概念。

1. Namespace

XAML 默认将下列 .NET Namespace 映射到 "http://schemas.microsoft.com/winfx/2006/xaml/presentation":

System.Windows

System.Windows.Automation

System.Windows.Controls

System.Windows.Controls.Primitives

System.Windows.Data

System.Windows.Documents

System.Windows.Forms.Integration

System.Windows.Ink

System.Windows.Input

System.Windows.Media

System.Windows.Media.Animation

System.Windows.Media.Effects

System.Windows.Media.Imaging

System.Windows.Media.Media3D

System.Windows.Media.TextFormatting

System.Windows.Navigation

System.Windows.Shapes

除了这个包含绝大多数 WPF 所需类型的主要命名空间外,还有一个是 XAML 专用的命名空间 (System.Windows.Markup) —— "http://schemas.microsoft.com/winfx/2006/xaml"。使用非默认命名空间的语法有点类似于 C# Namespace Alias, 我们需要添加一个前缀,比如下面示例中的 "x"。

<Window x:Class="Learn.WPF.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1">
<Grid>
<TextBox x:Name="txtUsername" Background="{x:Null}"></TextBox>
</Grid>
</Window>

我们还可以引入 CLR Namespace。

<collections:Hashtable
xmlns:collections="clr-namespace:System.Collections;assembly=mscorlib"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<sys:Int32 x:Key="key1">1</sys:Int32>
</collections:Hashtable>