wpf應用程序在啟動的時候會自動創建Main函數並調用Application實例的run(),從而啟動Application進程。Main函數在一個App.g.cs文件中,App.g.cs文件的位置在\obj\x86\Debug\App.g.cs。自動生成的Main函數如下:
/// <summary> /// Application Entry Point. /// </summary> [System.STAThreadAttribute()] [System.Diagnostics.DebuggerNonUserCodeAttribute()] public static void Main() { WpfApp1031.App app = new WpfApp1031.App(); app.InitializeComponent(); app.Run(); }
如果我們想在Main函數中獲取參數或做一些用戶驗證,就可以在此修改Main函數,但是你會發現項目關閉再重新啟動的時候,App.g.cs會重新生成,所以我們必須放棄在App.g.cs文件中修改Main函數。解決方案如下:
第一步:打開App.xaml文件的“屬性”窗口,修改生成操作:ApplicationDefinition 為Page。
第一步:我們可以在App.xaml.cs中重新寫Main函數,啟動主窗口的方法有三種,方法1比較常見。代碼如下:
public partial class App : Application { [STAThread] static void Main(string[] args) { //用戶驗證操作Start //...... //用戶驗證操作Start //方法1 Application app = new Application(); Window1 win1 = new Window1(); app.Run(win1); //方法2 //Application app = new Application(); //Window1 win1 = new Window1(); //app.MainWindow = win1; //win1.Show(); //app.Run(); //方法3 //Application app = new Application(); //app.StartupUri = new Uri("Window1.xaml", UriKind.Relative); //app.Run(); } }
第三步:修改項目的啟動對象為App類,默認(未設置)
重新生成就可以了。
各個Buid Action之間的區別 (生成操作的各個選項目前還不太明白,等以后慢慢了解吧!)
* None: 此文件不參與編譯也不被輸出。比如:工程中的文檔文件, readme.txt。
* Compile: 參與編譯並輸出。主要是代碼文件。
* Content: 不參與編譯,但會被輸出。
* Embedded Resource: 此文件被嵌入到主工程生成的DLL或exe中。主要是資源文件。
* ApplicationDefinition: 和Page類似,但只用於Silverlight的啟動頁面(默認是App.xaml)。
* Page: Silverligh中所有的usercontrol/page/childwindow xaml都屬於"Page” build,其它的build action不能將code behind文件和xaml文件連接起來。
* CodeAnalysisDictionary: 自定義的CodeAnalysis字典。
* Resource:embeds the file in a shared (by all files in the assembly with similar setting) assembly manifest resource named AppName.g.resources
* SplashScreen: Silverlight的歡迎界面。
* DesignData: Sample data types will be created as faux types. Use this Build Action when the sample data types are not creatable or have read-only properties that you want to defined sample data values for.
* DesignDataWithDesignTimeCreatableTypes: Sample data types will be created using the types defined in the sample data file. Use this Build Action when the sample data types are creatable using their default empty constructor.
* EntityDeploy: 適用於Entity框架。
經過嘗試,我們也可是自己重新創建一個program類來寫Main函數,然后修改項目的啟動對象為program類,代碼如下:
public class program : Application { [STAThread] static void Main() { //用戶驗證操作Start //...... //用戶驗證操作Start //方法1 Application app = new Application(); Window1 win1 = new Window1(); app.Run(win1); //方法2 //Application app = new Application(); //Window1 win1 = new Window1(); //app.MainWindow = win1; //win1.Show(); //app.Run(); //方法3 //Application app = new Application(); //app.StartupUri = new Uri("Window1.xaml", UriKind.Relative); //app.Run(); } }