zoukankan      html  css  js  c++  java
  • WPF教程(十)使用App.xaml

    WPF教程(十)使用App.xaml

    2016-10-07 21:37:09 seanbei 阅读数 12976 文章标签: c#wpf 更多

    分类专栏: 语言学习

    App.xaml是应用的声明起始点。
    在VS新建一个WPF应用,就能自动生成一个App.xaml,同时包含了后台代码文件App.xaml.cs。
    这两个文件都是局部类,和Window类非常相似,让你能够使用标记语言和后台代码。

    App.xaml.cs扩展了应用类,它是WPF窗口应用的中心类。.NET首先进入这个类的起始指令,从这里启动预想的窗口或者网页。同时这里订阅了重要的应用事件,如应用启动、未处理的异常等等。

    App.xaml最常使用的特性是定义全局资源,它们可能会在整个应用里面被使用或者访问,如全局样式。

    App.xaml结构

    自动生成的App.xaml代码如下:

    <Application x:Class="WpfTutorialSamples.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="MainWindow.xaml">
    
    <Application.Resources>
    </Application.Resources>
    
    </Application>

    主要来看StartupUri属性,它指示了启动应用的时候,加载哪个窗口或网页。在这里将加载MainWindow.xaml。可以通过替换来使用不同的窗体。

    有时候你想获取更多的控制,如窗口如何显示,什么时候显示。其实可以删去StartupUri及其值,然后在后台代码里实现。后面会讲。

    App.xaml.cs结构

    对应的代码如下:

    <span style="font-size:14px;">
    using System;
    using System.Collections.Generic;
    using System.Windows;
    
    namespace WpfTutorialSamples {
    
        public partial class App : Application{}
    
    }</span>

    从上面可以看到这个类是如何扩展应用类的,它允许我们在应用层填充内容。例如,可以订阅启动事件,用来指定启动窗口。

    看下面的例子:

    
     
    1. <span style="font-size:14px;"><Application x:Class="WpfTutorialSamples.App"

    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    4. Startup="Application_Startup">

    5. <Application.Resources></Application.Resources>

    6. </Application></span>

    StartupUri被一个启动事件的订阅所取代(通过XAML订阅事件会在后面将到)。在后台代码使用事件,如下:

    
     
    1. <span style="font-size:14px;">using System;

    2. using System.Collections.Generic;

    3. using System.Windows;

    4.  
    5. namespace WpfTutorialSamples

    6. {

    7. public partial class App : Application

    8. {

    9.  
    10. private void Application_Startup(object sender, StartupEventArgs e)

    11. {

    12. // Create the startup window

    13. MainWindow wnd = new MainWindow();

    14. // Do stuff here, e.g. to the window

    15. wnd.Title = "Something else";

    16. // Show the window

    17. wnd.Show();

    18. }

    19. }

    20. }</span>

    与前面使用StartupUri属性相比,这里可以在显示启动窗口之前对它进行操作,例如改变标题。尽管不是很常用,这可以订阅事件,或者显示一个启动界面。当你拥有所有的控制权,就有了很多种可能。在后面的章节我们会深入研究。

  • 相关阅读:
    挑战程序设计竞赛 2.1 最基础的“穷竭搜索”
    HDU 5145 NPY and girls(莫队算法+乘法逆元)
    BZOJ 4300 绝世好题(位运算)
    HDU 5724 Chess(博弈论)
    BZOJ 1177 [Apio2009]Oil(递推)
    Codeforces 706D Vasiliy's Multiset(可持久化字典树)
    HDU 3374 String Problem (KMP+最小最大表示)
    POJ 2758 Checking the Text(Hash+二分答案)
    HDU 5782 Cycle(KMP+Hash)
    POJ 3450 Corporate Identity(KMP)
  • 原文地址:https://www.cnblogs.com/grj001/p/12223779.html
Copyright © 2011-2022 走看看