WPF 学习笔记《2》——Hello world

创建一个简单WPF的应用程序,点击按钮,在文本框中显示“Hello WPF World”,我们通过此例来分析WPF应用程序的结构。

XAML文件如下:

<Window
xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class
="WpfApplication7.MainWindow"
x:Name
="Window"
xmlns:local
="clr-namespace:WpfApplication7"
Title
="Hello World"
Width
="254" Height="169">
<Grid>
<TextBox Height="45" HorizontalAlignment="Left" Margin="53,27,0,0" Name="textBox1" VerticalAlignment="Top" Width="128" />
<Button Content="Hello World" Height="23" HorizontalAlignment="Left" Margin="62,94,0,0" Name="button1" VerticalAlignment="Top" Width="111" Click="button1_Click" />
</Grid>
</Window>

后台代码:

using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfApplication7
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();

// 在此点下面插入创建对象所需的代码。
}

private void button1_Click(object sender, RoutedEventArgs e)
{
textBox1.Text
= "Hello World";
}
}
}

显示效果:

分析此项目的代码得到如下几点:

  • 与基于Windows的应用程序,Web应用程序类型,WPF的窗体也属于“类型化窗体”,即每一个窗体均继承于“System.Windows.Window”类
  • 对于WPF控件的属性,可以在XAML文件中声明设置,也可以在代码中设置(这一点和ASP.Net WebControl的属性设置类似)
  • 在XAML文件Windows声明中有两个命名空间
    • xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" :将整个 Windows Presentation Foundation (WPF) 命名空间映射为默认命名空间
    • xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" :映射单独的可扩展应用程序标记语言 (XAML) 命名空间,通常将其映射为 x: 前缀
    • 注意这两个命名空间引用的是URI而不是真实存在的URL
  • 对于控件的某些属性,可以直接设置,也可以单独设置。很多 WPF 类型或这些类型的成员扩展了基本字符串属性处理行为,因此更复杂的对象类型的实例可通过字符串指定为属性值。在代码级别,此处理是通过指定处理字符串属性值的 CLR 类型转换器来完成的。如Margin。在本例中StackPanel的Margin属性直接以字符串形式给出,而Button的Margin则是通过CLR映射给出的。
  • 如在代码中使用某控件对象,则该对象需在XAML声明中以x:Name方式指定,如在代码中不需访问此控件对象的属性或方法,则不需指定
  • Window声明中的x:Class指定了该XAML文件所对应的后台类,事件的处理方法就是写在这个类中的
  • WPF采用的事件处理与ASP.Net类似,在XAML文件的控件声明位置进行事件绑定,在后台类中给出事件处理方法的具体代码
posted @ 2011-08-17 14:33  徐文峰  阅读(184)  评论(0)    收藏  举报