如果不用VS的WPF項目模板,如何手工創建一個WPF程序呢?我們來模仿WPF模板,創建一個最簡單的WPF程序。
第一步:文件——新建——項目——空項目,創建一個空項目。
第二步:添加引用,PresentationFramework,PresentationCore,WindowsBase,System,System.Xaml,這幾個是WPF的核心dll。
第三步:在項目上右鍵添加新建項,添加兩個“xml文件”,分別命名為App.xaml和MainWindow.xaml。可以看出,xaml文件其實就是xml文件。
第四步:同第二步,添加兩個代碼文件,即空白c#代碼文件,分別命名為App.xaml.cs和MainWindow.xaml.cs。可以看到,這兩個文件自動變成第二步生成的兩個文件的code-behind文件。
第五步:添加Xaml和C#代碼:
App.xaml和MainWindow.xaml中刪除自動生成的xml文件頭,分別添加如下Xaml標記:
1
2
3
4
5
6
7
8
|
<Application x:Class= "WpfApp.App" xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x= "http://schemas.microsoft.com/winfx/2006/xaml" StartupUri= "MainWindow.xaml" > <Application.Resources> </Application.Resources> </Application> |
1
2
3
4
5
6
7
8
|
<Window x:Class= "WpfApp.MainWindow" xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x= "http://schemas.microsoft.com/winfx/2006/xaml" Title= "MainWindow" Height= "350" Width= "525" > <Grid> </Grid> </Window> |
App.xaml.cs和MainWindow.xaml.cs中分別添加類似如下的代碼:
1
2
3
4
5
6
7
8
9
10
11
|
using System.Windows; namespace WpfApp { /// <summary> /// App.xaml 的交互邏輯 /// </summary> public partial class App : Application { } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
using System.Windows; namespace WpfApp { /// <summary> /// MainWindow.xaml 的交互邏輯 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } } } |
第六步:如果此時編譯就會報錯,提示沒有找到Main函數入口,這個Main函數其實不用自己添加,系統會自動生成的。打開App.xaml的文件屬性,將生成操作由Page改為ApplicationDefinition。
第七步:此時應該已經可以正常運行了,系統默認輸出是控制臺應用程序,可以打開項目屬性頁,將輸出類型改為Windows應用程序。
至此,一個模仿VS的WPF項目模板的最簡單的WPF程序就OK了。
以上就是本文的全部內容,希望對大家的學習有所幫助。