技术开发 频道

详细解析WPF中的应用程序模型

  (4)现在让我们定义联系人的集合。您需要在项目中添加一个新的文本文件contacts.txt。您可以通过Solution Explorer,右键点击项目,选择Add?New Item随后在对话框中选择’Text File‘。将以下内容复制到文件里:

Joe;Developer;jd@spaces.msn.com;http://spaces.msn.com;1 North First St, Redmond, WA 98052; 2 South First St, Redmond, WA 98052
Jane;Tester;jt@spaces.msn.com;http://spaces.msn.com;101 Baker St, Bellevue, WA 98055; 202 Smith St, Redmond, WA 98052

   每行都是一个联系人的信息。一旦contacts.txt文件被创建,在Solution Explorer里选中它。文件的属性会出现在下方的Properties窗口。如果这个窗口没有出现,请右键点击这个文件,选择Properties。

  ·请注意Build Action这个属性的值是’Content’。这个值告诉WPF的MSBuild系统,把这个文件作为伴随应用程序的松散内容。

  ·Copy to Output Directory这个属性的值是’Do not copy‘,请把它改成’Copy if newer’。这一步确保一旦contacts.txt文件被修改了,新的版本会被复制到版本的输出目录里。

  (5)为了控制应用程序启动和退出时的操作,我们下面要处理Application Startup和Exit事件。请在App.xaml.cs中添加下面的代码:

public App()
{
}

void AppStartup(object sender, StartupEventArgs args)
{
    MainWindow mainWindow
= new MainWindow();
    mainWindow.WindowStartupLocation
= WindowStartupLocation.CenterScreen;

    mainWindow.Show();
}

private void AppExit(Object sender, ExitEventArgs e)
{
}

 

  双击MyApp.xaml察看XAML,将以下标记语句添加到MyApp.xaml里,这样Startup事件就与代码绑定了。您需要删除StartupUri属性,以便由Startup事件的代码来处理MainWindow的加载工作。

<Application
    
x:Class="AddressBook.App"
    xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    StartupUri
="MainWindow.xaml"
    Startup
="AppStartup"
    Exit
="AppExit" >
  
<Application.Resources>
  
</Application.Resources>
</Application>

 

  (6)下面我们创建基本的UI。UI由一个Window组成,Window里有一个Grid并进一步包含一个DockPanel。DockPanel用来显示菜单栏,工具栏,状态栏,和一个罗列所有联系人的左面板。右边的面板则用来显示当前选中的联系人的详细信息。

  在MainWindow.xaml文件里,我们从外层的Grid开始。首先将它命名为DocumentRoot:当您双击MainWindow.xaml时,您会同时看到Design选项卡和XAML选项卡。请选择XAML选项卡来编辑xaml:

<Window x:Class="AddressBook.MainWindow"
    xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
    Title
="AddressBook"
    Loaded
="WindowLoaded"
    SizeToContent
="WidthAndHeight"
    MinWidth
="640"
    MinHeight
="480">

  
<Grid Background="White" Name="DocumentRoot">
    
<Grid.ColumnDefinitions>
      
<ColumnDefinition Width="200"/>
      
<ColumnDefinition Width="*"/>
    
</Grid.ColumnDefinitions>
    
<Grid.RowDefinitions>
      
<RowDefinition Height="Auto"/>
      
<!-- Menu -->
      
<RowDefinition Height="Auto"/>
      
<!-- Tool Bar -->
      
<RowDefinition Height="*"/>
      
<!-- Content Area -->
      
<RowDefinition Height="Auto"/>
      
<!-- Status Bar -->
    
</Grid.RowDefinitions>

  
</Grid>
</Window>

 

1
相关文章