摘自:https://www.cnblogs.com/JerryMouseLi/p/11812972.html
一個基於Net Core3.0的WPF框架Hello World實例
目錄
一個基於Net Core3.0的WPF框架Hello World實例
1.創建WPF解決方案
1.1 創建Net Core版本的WPF工程
1.2 指定項目名稱,路徑,解決方案名稱
2. 依賴庫和4個程序文件介紹
2.1 框架依賴庫
依賴Microsoft.NETCore.App跟Microsoft.WindowsDesktop.App.WPF
2.2 生成文件說明
生成4個文件App.xaml,App.xaml.cs,MainWindow.xaml,MainWindow.xaml.cs
2.2.1 App.xaml
App.xaml設置應用程序的起始文件與資源。這里的資源一般指:
- 其他xaml樣式文件的路徑;
- 設置主題色,背景色,窗體樣式;
- 按鈕樣式,菜單樣式;
- 自定義彈出樣式,自定義滾動條寬度;
......等等
App.xaml文件內容如下:
<Application x:Class="IBMSManager.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:IBMSManager" StartupUri="MainWindow.xaml"> <Application.Resources> 系統資源定義區 </Application.Resources> </Application>
- Application x:Class="IBMSManager.App" 表示Application后台類
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 表示WPF應用程序的默認命名空間映射
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 映射可擴展應用程序標記語言(XAML)的擴展命名空間,通常將其映射為X前綴
- xmlns:local="clr-namespace:IBMSManager" 項目的名稱就是IBMSManager
- StartupUri="MainWindow.xaml" 表示要啟動的應用窗體
2.2.2 App.xaml.cs
App.xaml的后台文件,集成自System.Windows.Application,用於處理整個WPF應用程序相關的設置。
2.2.3 MainWindow.xaml
WPF應用程序界面與XAML設計文件
<Window x:Class="IBMSManager.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:IBMSManager" mc:Ignorable="d" Title="IBMSManager" Height="450" Width="800"> <Grid> </Grid> </Window>
- Windows對象實例基類
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"設計時的狀態的命名空間
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"標記兼容性相關的命名空間
- mc:Ignorable="d",d:DesignWidth是設計時的,所以,Ignorable="d"就是告訴編譯器在實際運行時,忽略設計時設置的值。
- Title="MainWindow" Height="450" Width="800" 屬性設置,這里講Title改為IBMSManager
- 用來划分頁面的分割與區域,填放按鈕等頁面元素
2.2.4 MainWindow.xaml.cs
MainWindow.xaml的后台文件,集成自System.Windows.Window,用於編寫MainWindow.xaml 的交互邏輯代碼
3. Hello World實例
3.1 拖動按鈕控件到WPF窗體中
MainWindow.xaml文件中會自動添加如下代碼
<Grid> <Button Content="Button" HorizontalAlignment="Right" Margin="0,0,554,254" VerticalAlignment="Bottom"/> </Grid>
代碼主要在Grid標簽中描述了按鈕的屬性
3.2 設計時中雙擊按鈕添加按鈕事件
MainWindow.xaml文件中會自動添加Click="Button_Click
<Grid> <Button Content="Button" HorizontalAlignment="Right" Margin="0,0,554,254" VerticalAlignment="Bottom" Click="Button_Click"/> </Grid>
后台MainWindow.xaml.cs文件中自動添加了事件處理函數
private void Button_Click(object sender, RoutedEventArgs e) { }
3.3 事件處理函數中添加消息提示框
點擊按鈕后,出現消息提示框Hello World。
private void Button_Click(object sender, RoutedEventArgs e) { MessageBox.Show("Hello World!"); }
3.4 效果如下
The Sky is the limit.