您的位置:首页 > 移动开发

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

2011-06-18 00:24 1056 查看
使用代码构建一个简单的 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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐