我有一个wpf应用程序,我创建了一个登录窗口,用于构建应用程序的连接字符串。我在关闭第一个对话框并旋转打开后面的MainWindow时遇到问题。我认为一个关闭事件正在冒出登录对话框并卡在MainWindow中,因为只要我在代码隐藏中创建MainWindow对象并调用Show()它就会直接移过我的Startup事件处理程序并进入我的构造函数然后onWosing MainWindow的处理程序,而不显示窗口本身。 app.xaml指定了ShutdownMode =“OnMainWindowClose”。
private void Application_Startup(object sender, StartupEventArgs e)
{
try
{
Chooser thechooser = new Chooser();
thechooser.ShowDialog();
}
catch (Exception ex)
{
}
//initialize datalayer
dataLayer = new Mxxx41.DAL(this.CurrentConnectionString);
MainWindow appmainwindow = new MainWindow();
Application.Current.MainWindow = appmainwindow;
appmainwindow.Activate();
appmainwindow.Show();
}
private void LogInButton_Click(object sender, RoutedEventArgs e)
{
//get ip from listbox selection
XmlElement currentelement = (XmlElement)Listbox.SelectedItem;
string ip = ((string)currentelement.Attributes["IP"].Value);
string instancename = string.Empty;
if (!((string)currentelement.Attributes["InstanceName"].Value == string.Empty))
{
instancename = ((string)currentelement.Attributes["InstanceName"].Value);
}
//ping that IP
Boolean pingresult = ping.PingHost(ip);
Boolean sqlresult = false;
if (pingresult)
{
if (!(String.IsNullOrEmpty("instancename")))
{
ip = string.Format("{0}\\{1}", ip, instancename);
}
//build connection string with that IP
string connstr = BuildConnStr(ip);
//create datalayer
Mxxx41.DAL datalayer = new Mxxx41.DAL(connstr);
//validate credentials
DataSet data = datalayer.getDataSet("login_checkcredentials", CommandType.StoredProcedure, datalayer.CreateParameter("@username", SqlDbType.VarChar, this.UsernameTextbox.Text), datalayer.CreateParameter("@password", SqlDbType.VarChar, this.PasswordTextbox.Text));
if (data.Tables[0].Rows.Count > 0)
{
sqlresult = true;
//log in user
//build new user code omitted for brevity
App myAppReference = ((App)Application.Current);
myAppReference.CurrentUser = thisuser;
myAppReference.CurrentConnectionString = connstr;
//close window
this.Close(); //this is the close event I think is causing issues.
}
}
else
{
ErrorLabel.Content = string.Format("{0}{1}", "could not ping selected Host :", ip);
}
//return true
}
public MainWindow(){
this.InitializeComponent();
this.SideBarExpander.IsExpanded = true;
this.Loaded += onLoaded;
this.Closed += onClosed;
this.Closing += onClosing;
try
{
//this.DataLayer = ((Mxxx41.DAL)MyDemoApp.App.Current.Properties["DataLayer"]);
App myAppReference = ((App)Application.Current);
this.DataLayer = myAppReference.GetDataLayer();
}
catch //catch everything for the moment
{
this.DataBaseConnectionError = true;
}
ExceptionList = new List<Error>();
}
有人可以帮我解决这个问题吗?
答案 0 :(得分:4)
问题可能出在ShutdownMode="OnMainWindowClose"
。 Wpf认为打开的第一个窗口是“主窗口”。在您的情况下,wpf将您的登录窗口视为主窗口,并在关闭时退出应用程序。
尝试将关机模式更改为OnLastWindowClose
或OnExplicitShutdown
。
来自MSDN:
OnMainWindowClose :当主窗口关闭或调用Shutdown时,应用程序会关闭。
OnExplicitShutdown :只有在调用Shutdown时,应用程序才会关闭。