对于WPF应用程序,在Visual Studio和Expression Blend中,自定义的窗体均继承System.Windows.Window类.大家都可能听说过或者看过Applications = Code + Markup: A Guide to the Microsoft Windows Presentation Foundation这本书,它里面就是用XAML和后台代码两种形式来实现同一个功能,那么我们这里定义的窗体也由两部分组成:
1、 XAML文件,在这里面通常全部写UI的东西(希望大家还记得这两幅图)
2、后台代码文件
namespace WPFApplications
{
/// <summary>
/// Interaction logic for Window5.xaml
/// </summary>
public partial class Window5 : Window
{
public Window5()
{
InitializeComponent();
}
private void btnOK_Click(object sender, RoutedEventArgs e)
{
lblHello.Content = "Hello World Changed";
}
}
}
也可以将后台代码放在XAML文件中,上面的例子可以改写为:
<Window x:Class="WPFApplications.Window5"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window5" Height="300" Width="300">
<StackPanel>
<Label x:Name="lblHello">Hello,World!</Label>
<Button x:Name="btnOK" Width="88" Height="22" Content="Click"
Click="btnOK_Click"/>
<x:Code>
<![CDATA[
void btnOK_Click(object sender, System.Windows.RoutedEventArgs e)
{
lblHello.Content = "Hello World Changed";
}
]]>
</x:Code>
</StackPanel>
</Window>
1、显示窗体
2、关闭窗体
3、窗体的激活
4、窗体的生命周期
为了证实上面的结论,我们用下面的代码进行测试:
public partial class Window3 : Window
{
public Window3()
{
this.Activated += new EventHandler(Window1_Activated);
this.Closing += new System.ComponentModel.CancelEventHandler(Window1_Closing);
this.ContentRendered += new EventHandler(Window1_ContentRendered);
this.Deactivated += new EventHandler(Window1_Deactivated);
this.Loaded += new RoutedEventHandler(Window1_Loaded);
this.Closed += new EventHandler(Window1_Closed);
this.Unloaded += new RoutedEventHandler(Window1_Unloaded);
this.SourceInitialized += new EventHandler(Window1_SourceInitialized);
InitializeComponent();
}
void Window1_Unloaded(object sender, RoutedEventArgs e)
{
Debug.WriteLine("Unloaded");
}
void Window1_SourceInitialized(object sender, EventArgs e)
{
Debug.WriteLine("SourceInitialized");
}
void Window1_Loaded(object sender, RoutedEventArgs e)
{
Debug.WriteLine("Loaded");
}
void Window1_Deactivated(object sender, EventArgs e)
{
Debug.WriteLine("Deactivated");
}
void Window1_ContentRendered(object sender, EventArgs e)
{
Debug.WriteLine("ContentRendered");
}
void Window1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
Debug.WriteLine("Closing");
MessageBoxResult dr = MessageBox.Show("Cancel the window?",
"Answer", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (dr == MessageBoxResult.No)
{
e.Cancel = true;
}
}
void Window1_Closed(object sender, EventArgs e)
{
Debug.WriteLine("Closed");
}
void Window1_Activated(object sender, EventArgs e)
{
Debug.WriteLine("Activated");
}
}
执行结果为:
WPF窗体的详细的属性、方法、事件请参考MSDN,有很多的属性、方法、事件与Windows应用程序中 System.Windows.Forms.Form类颇为相似,其中常用的一些属性、方法、事件有:
联系客服