【发布时间】:2013-07-15 05:16:35
【问题描述】:
我在 Microsoft Expression Blend 4 中创建了一个准系统 WPF 项目。
然后我在 Visual Studio 2012 中打开了该项目,并向该项目添加了一个简单的类。
我将应用程序属性设置为使用此类作为启动对象。
我创建了一个新的主窗口,然后对对象使用了 show 函数。
窗口会弹出一毫秒,然后关闭。
如何调用 MainWindow 使其保持打开状态?
Class1.cs
//This is the Class I created
using System;
using System.Collections.Generic;
namespace WpfApplication5
{
static class Class1
{
[STAThread]
static void Main()
{
MainWindow winMain = new MainWindow();
winMain.Show();
}
}
}
MainWindow.xaml.cs
//This is the Mainwindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace WpfApplication5
{
public partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
}
}
}
MainWindow.xaml
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="WpfApplication5.MainWindow"
x:Name="Window"
Title="MainWindow"
Width="640" Height="480">
<Grid x:Name="LayoutRoot"/>
</Window>
App.xaml
<Application
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="WpfApplication5.App"
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>
App.xaml.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Windows;
namespace WpfApplication5
{
public partial class App : Application
{
}
}
【问题讨论】:
-
为什么需要 Class1.cs ?您已经通过设置 StartupUri 在 App.xaml 中定义了应用程序的入口点。
-
我想知道你在编译项目时没有得到任何异常,因为设置了 2 个入口点。所以最好删除 [STAThread] static void Main() { MainWindow winMain = new MainWindow(); winMain.Show(); }
-
我使用 Class1.cs 作为最简单的例子,Class1 最终将包含核心程序代码,并调用其他类,我将需要显示几个窗口,具体取决于什么发生在代码中。因此需要/想要通过代码调用 xaml 窗口。我没有收到任何异常,到目前为止没有人回答问题。我尝试从 App.xaml 中删除 Startupuri 调用,但也没有用。谢谢!
-
您可以从您的代码中创建和显示任意数量的窗口。只是您不需要 Class1.cs 中的 Main 方法再次指定应用程序的入口点。
-
我从 App.xaml 中删除了另一个入口点,因此不再有 2 个入口点,调用主窗口使其消失。那么我该如何称呼它,或任何其他窗口,从哪里来?如果我有一个 mainwindow2,我会怎么称呼它?谢谢!