zoukankan      html  css  js  c++  java
  • 2000条你应知的WPF小姿势 基础篇<34-39 Unhandled Exceptions和Resource>

      在正文开始之前需要介绍一个人:Sean Sexton. 来自明尼苏达双城的软件工程师。最为出色的是他维护了两个博客:2,000Things You Should Know About C#  和 2,000 Things You Should Know About WPF 。他以类似微博式的150字简短语言来每天更新一条WPF和C#重要又容易被遗忘的知识。Follow他的博客也有一段日子了,很希望能够分享给大家。

      本系列我不仅会翻译他的每一个tip,也会加入自己开发之中的看法和见解。本系列我希望自己也能和他一样坚持下来,每天的进步才能促成伟大。

      在这里郑重说明.该系列是基于Sean Sexton先生的英文博客, Sean Sexton拥有全部版权和撤销权利。

      前文:<1-7> , <8-14>,<15-21>,<22-27>, <28-33>

      [小九的学堂,致力于以平凡的语言描述不平凡的技术。如要转载,请注明来源:小九的学堂cnblogs.com/xfuture]


      #34 WPF程序退出事件处理

      当WPF程序点击关闭或者退出时,你可以在Application.Exit事件里添加处理退出逻辑

      

    <Application x:Class="WpfApplication4.App"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 StartupUri="MainWindow.xaml"
                 Exit="Application_Exit">
    </Application>
     
    private void Application_Exit(object sender, ExitEventArgs e)
    {
        // Perform tasks at application exit
    }

      Exit事件会在应用退出和Windows退出时触发,顺序在Windows的SessionEnding事件后面。

      

      #35 Unhandled Exceptions

      WPF应用程序当遇到异常Exception时,如果代码中并没有对其进行处理就会抛出,导致了应用程序异常关闭。类似下图:

      

      异常抛出时,WPF应用会立刻关闭。用户会丢失所有的操作和得不到多余的信息。其实就是程序员最不愿意碰到的情况,自己写的程序崩掉了。

      处理方法是你可以在Application.DispatcherUnhandledException中处理所有抛出的异常。在这里我们可以将异常信息展示出来而且通过设置Handled属性来阻止程序崩溃。如下图:

      

    private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
    {
        string friendlyMsg = string.Format("SO sorry that something went wrong.  The error was: [{0}]", e.Exception.Message);
        string caption = "Error";
        MessageBox.Show(friendlyMsg, caption, MessageBoxButton.OK, MessageBoxImage.Error);
     
        // Signal that we handled things--prevents Application from exiting
        e.Handled = true;
    }

      

      

      #36 Application-Scoped Properties

      

      Application类包含了一个Properties的属性,它是属性集合的字典 IDictionary,存储Key/Value。你可是存储在Application要用到的所有属性在这个字典里。

      在任何线程都可以读写Properties,它是线程安全的。

      

    private void Application_Startup(object sender, StartupEventArgs e)
    {
        this.Properties.Add("Debug", false);
        this.Properties.Add("Logger", null);
     
        // Set properties based on command line parameters
        foreach (string a in e.Args)
        {
            if (a.ToLower() == "/debug")
                this.Properties["Debug"] = true;
            else if (a.ToLower() == "/logging")
                this.Properties["Logger"] = new MyAppLogger("Logfile.txt");
        }
    }

      

      #37 Resource

      WPF和Silverlight,Resource是指可以在多处使用的.net对象或者值。Resource是WPF和Silverlight可以重用的资源。

      Resources存储在应用程序的资源字典的,存储的对象是Key/Value的形式。资源通常储存的对象有:styles, templates, brushes and colors, storyboards, transforms, or 3D matrices

      

      #38 定义和使用Resource

      你可以将Resource和MainApplication关联起来,这样你就可以在任何地方使用该资源。

      你可以在App.xaml里定义资源:

      

    <Application x:Class="WpfApplication.App"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 StartupUri="MainWindow.xaml" Startup="Application_Startup" >
        <Application.Resources>
            <SolidColorBrush x:Key="greenBrush"  Color="Green"/>
        </Application.Resources>
    </Application>

      在任意的UserControl或者Window都可以通过引用StaticResource来引用这个resource。

      

    <Window x:Class="WpfApplication.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="224" Width="334">
        <Grid>
            <Button Content="Button" Background="{StaticResource greenBrush}"
                    Height="23" HorizontalAlignment="Left" Margin="60,57,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
        </Grid>
    </Window>

      

      #39 c# code使用resource

      Resource Dictionary存储的key/value形式的对象是DictionaryEntry类型的。你可以在Xaml中定义这个资源并且在C# code中来使用。

      具体实现如下:

      

    <Application.Resources>
        <SolidColorBrush x:Key="greenBrush"  Color="Green"/>
    </Application.Resources>

      Key是greenBrush Value是一个SolidColorBrush, Color属性是Green。

      C# code中得到该resource:

      

    SolidColorBrush br = (SolidColorBrush)Application.Current.Resources["greenBrush"];


     

      后篇会对WPF内部机制继续做探索,敬请关注!

      如果觉得有帮助,右下角赞一下吧~ (* *)

  • 相关阅读:
    Node.js Express框架
    Node.js Web模块
    Node.js 工具模块
    Node.js GET/POST请求
    Node.js 文件系统
    Node.js 常用工具
    【day03】Xhtml
    【day02】Xhtml
    【紫书】【重要】Not so Mobile UVA
    【紫书】Tree UVA
  • 原文地址:https://www.cnblogs.com/xfuture/p/3784221.html
Copyright © 2011-2022 走看看