zoukankan      html  css  js  c++  java
  • 《Applications=Code+Markup》读书札记(2)——创建一个简单的 WPF 程序的代码结构及关于 Window 实例位置设置问题

    使用代码构建一个简单的 WPF 程序可能有多种代码结构:

    1、最简短的。读者可以看下面的代码:MyWindow 继承自 Window 类,在入口函数里面创建 Application 实例并使用该对象 Run 方法调用 Window 实例的 Show 方法。这种实现方式就是可读性太差,让人摸不着头脑。

    using System;
    using System.Windows;

    namespace WpfAppByCode
    {
    class MyWindow : Window
    {
    [STAThread]
    public static void Main()
    {
    new Application().Run(new MyWindow());
    }
    }
    }

    待续……

    PS:关于 Window 实例位置设置问题

    很多读者首先想到的可能是 WindowStartupLocation 枚举——不就给 Window 实例的 WindowStartupLocation 属性赋予 WindowStartupLocation 枚举的一个常量么?聪明的读者,你有没想过这里面的具体实现呢?其实和 Window 实例位置相关的属性有 Width、Height、Left 和 Top,而且有先后顺序,一般地,我们得先给 Width 和 Height 赋好值后才去指定其 Left 和 Top 属性,否则我们的代码会失效,有可能我们的本意是让窗口居中而编译运行后却发现窗口出现在系统默认位置(WindowStartupLocation.Manual)。在这里需要注意,如果在 Window 构造函数里没有指定 Width 和 Height 属性就别在构造函数里指定 Left 和 Top 属性,而应在 Window 实例的 Loaded 事件的事件处理器里指定。

    using System;
    using System.Windows;

    namespace WpfAppByCode
    {
    class InheritWindow : Window
    {
    [STAThread]
    public static void Main()
    {
    new Application().Run(new InheritWindow());
    }

    public InheritWindow()
    {
    this.Title = "稻草人";
    this.Loaded += WindowOnLoaded;
    }

    private void WindowOnLoaded(object sender, RoutedEventArgs e)
    {
    this.Left = (SystemParameters.PrimaryScreenWidth - this.ActualWidth) / 2;
    this.Top = (SystemParameters.PrimaryScreenHeight - this.ActualHeight) / 2;
    }
    }
    }


  • 相关阅读:
    Java中String的intern方法
    3.7测试复盘
    3.6测试复盘
    LTMU论文解析
    移动机器人相机模型:从相机移动到二维图像
    一步步分析MIPS数据通路(单周期)
    Slam笔记I
    如何理解SiamRPN++?
    如何使用Pytorch迅速写一个Mnist数据分类器
    PySide2的This application failed to start because no Qt platform plugin could be initialized解决方式
  • 原文地址:https://www.cnblogs.com/daocaoren/p/2084037.html
Copyright © 2011-2022 走看看