29.1 XAML 概述
XAML(Extensible Application Markup Language)是Windows Presentation Foundation(WPF)的一部分,是微软开发的一种基于XML、基于声明,用于初始化结构化值和对象的用户界面描述语言,它有着HTML的外观,又揉合了XML语法的本质,例如:可以使用<Button>标签设置按钮(Button)。它类似Linux平台下的glade。至于WinFX XAML Browser Application(XBAP)是用XAML作界面描述,在浏览器中运行的程序,可取代过去的ActiveX、Java Applet、Flash。
XAML本质上属于一种.NET编程语言,属于通用语言运行库(Common Language Runtime),同C#、VB.NET等同。与HTML类似,特点是用来描述用户界面。XAML的语法格式为:<Application... />,Application是必备的基本元素。XAML可以定义2D和3D对象、旋转(rotations)、动画(animations),以及各式各样的效果。
29.2 示例
29.2.1元素如何映射到.net对象上
下面利用C#控制台项目在Window中通过编程方式创建一个Button对象。需要引用程序集:PresentationFramework,PresentationCore,WindowBase,System.Xaml。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace Wrox.ProCSharp.XAML
{
class Program
{
[STAThread]
static void Main(string[] args)
{
var b = new Button
{
Content = "Click Me"
};
var w = new Window
{
Title = "Code Demo",
Content = b
};
var app = new Application();
app.Run();
}
}
}
也可以使用XAML代码创建类似UI
<Window x:Class="MyWindow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="Click Here"/>
</Grid>
</Window>
29.2.2 使用自定义.net类
定义一个简单的Person类。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyWindow
{
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public override string ToString()
{
return string.Format("{0}{1}",FirstName,LastName);
}
}
}
MainWindow.xaml
<Window x:Class="MyWindow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyWindow"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="Click Here" Width="100" Height="100"/>
<ListBox Margin="35,10,381,206">
<local:Person FirstName="zzh" LastName="zzh" />
<local:Person FirstName="syj" LastName="syj" />
</ListBox>
</Grid>
</Window>
29.2.3 把属性用作特性
<Button Content="Click Here" Width="100" Height="100" Background="LightGoldenrodYellow"/>
29.2.4 把属性用作元素
<Button Click="OnButtonClick" Margin="141,10,240,229">
Click Me!
<Button.Background>
<LinearGradientBrush StartPoint="0.5,0.0" EndPoint="0.5, 1.0">
<LinearGradientBrush.GradientStops>
<GradientStopCollection>
<GradientStop Offset="0" Color="Yellow" />
<GradientStop Offset="0.3" Color="Orange" />
<GradientStop Offset="0.7" Color="Red" />
<GradientStop Offset="1" Color="DarkRed" />
</GradientStopCollection>
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</Button.Background>
</Button>
网友评论