框架
簡介
下面是幾種常見基于.Net的界面開發(fā)框架,都是Microsoft提供,下面簡介由GPT生成
WinForms (Windows Forms
WPF (Windows Presentation Foundation)
UWP (Universal Windows Platform)
MAUI (Multi-platform App UI)
-
WinForms(Windows Forms):
- 介紹: WinForms是由Microsoft提供的用于開發(fā)Windows桌面應(yīng)用程序的UI框架。它使用簡單的拖放界面進行用戶界面的構(gòu)建,并基于.NET框架。
- 主要特點:
- 使用可視化設(shè)計器進行快速應(yīng)用程序開發(fā)(RAD)。
- 事件驅(qū)動的編程模型。
- 與Windows API直接集成。
-
WPF(Windows Presentation Foundation):
- 介紹: WPF是用于構(gòu)建具有豐富用戶界面的Windows桌面應(yīng)用程序的框架。與WinForms相比,它提供了更現(xiàn)代和靈活的UI開發(fā)方法。
- 主要特點:
- 強大的數(shù)據(jù)綁定和模板系統(tǒng)。
- 分辨率獨立的矢量圖形。
- 可擴展和可定制的控件。
- UI和業(yè)務(wù)邏輯的分離。
-
UWP(Universal Windows Platform):
- 介紹: UWP是由Microsoft引入的平臺,用于創(chuàng)建可以在各種Windows設(shè)備上運行的通用應(yīng)用程序,包括PC、平板、手機、Xbox、HoloLens等。它是Windows 10生態(tài)系統(tǒng)的一部分。
- 主要特點:
- 自適應(yīng)用戶界面,適應(yīng)不同設(shè)備形狀。
- 安全性和性能改進。
- 與Windows 10功能的集成,如Cortana和Live Tiles。
-
MAUI(Multi-platform App UI):
- 介紹: MAUI是由Microsoft推出的現(xiàn)代跨平臺框架,用于從單一代碼庫構(gòu)建適用于iOS、Android、Windows和macOS的本機應(yīng)用程序。它是Xamarin.Forms的演進,是.NET MAUI堆棧的一部分。
- 主要特點:
- 單一代碼庫適用于多個平臺。
- 支持每個平臺的本機UI控件。
- 與.NET 6及更高版本集成。
- 面向各種設(shè)備,包括桌面和移動設(shè)備。
選擇
winform過于古早
uwp的話,我們就用windows電腦,沒必要
maui因為跨平臺,導致了其臃腫
所以我們選擇WPF,下面文章也是主要講WPF的
UI
設(shè)計思路
先根據(jù)功能,設(shè)計布局
然后就是如果項目比較大,要考慮設(shè)計模式的選取,讓前后端分離
控件
因為UI的開發(fā)都是基于界面和控件的,而我們常用的控件都大同小異,需要的時候自行查閱文檔就好了
常用
信息類 label
編輯類 文本編輯 textbox 狀態(tài)編輯 checkbox
按鈕 button
添加方式
拖拽添加
代碼添加
布局
定位
anchor,錨定某個邊緣
dock,???按彈出的選項進行設(shè)置
重寫Onlayout函數(shù)(布局改變時觸發(fā))
分組
panel,多層次布局,將控件綁定到panel上,便于組合整體控制
事件
即界面獲取操作,傳到后端進行相應(yīng)
winform
項目結(jié)構(gòu)
VS選擇基于C#的和.Net的窗體應(yīng)用創(chuàng)建
直接運行,可以看到一個空的界面
然后可以看解決方案管理,可以看到有
- Form1.cs這個是界面設(shè)計文件,直接打開展示UI,可以右鍵查看代碼
- Form1.Designer.cs,由我們的設(shè)計自動生成的底層代碼,由設(shè)計文件調(diào)用
- 上面兩個是同一個類分在不同的文件,前者處理事件,后者處理布局
- Form.resx
- program.cs 程序入口,
new Form1()
來示例化我們的窗口
通過拖拽添加控件,通過屬性添加事件.界面的主要代碼都在designer中,我們最好不要動它,需要的改動都在Form1.cs中
因為應(yīng)用場景少,所以不深入學習
WPF
WPF入門基礎(chǔ)教程系列
項目結(jié)構(gòu)
- App.xaml
StartupUri
設(shè)置啟動的窗口,Resources
樣式模板 - MainWindow.xaml 拖拽布局,可實時渲染
然后我們直接運行項目,可以看到一個空白窗口
xaml
xaml是一種基于xml的標記語言,用于定義UI和屬性,這里面都會根據(jù)xaml生成對應(yīng)的cs文件
就下面這個語法
<CMD ..... />
等價于<CMD>.....</CMD>
我們看``MainWindow.xaml`
<Window x:Class="WPF.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:WPF"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
</Grid>
</Window>
解釋如下
-
<Window>
元素:-
x:Class="WPF.MainWindow"
:這個屬性指定了窗口的類名。在這里,窗口的類名是MainWindow
,它與代碼中的類名相對應(yīng)。這個屬性通常用于將XAML文件與后端代碼(例如C#)中的類關(guān)聯(lián)起來。
-
-
命名空間聲明:
-
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
:指定默認的XML命名空間,該命名空間用于定義WPF的基本呈現(xiàn)元素,如窗口、面板、按鈕等。 -
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
:指定XAML專用命名空間,其中包含一些用于XAML文件的特殊屬性。
-
-
附加的命名空間聲明:
-
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
:用于Blend工具的命名空間,該工具通常用于設(shè)計和交互式開發(fā)。 -
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
:定義了一些用于在不同XAML編譯器版本之間保持兼容性的屬性。
-
-
本地命名空間聲明:
-
xmlns:local="clr-namespace:WPF"
:指定了一個本地的命名空間,它與命名空間WPF
相關(guān)聯(lián)。這使得在XAML文件中可以引用WPF
命名空間中定義的類和資源。
-
-
mc:Ignorable="d"
:- 這個屬性告訴編譯器在處理未知的
d
前綴時忽略錯誤。在這里,d
是Blend工具的命名空間,而Ignorable
屬性允許在不影響編譯的情況下忽略這個未知的前綴。
- 這個屬性告訴編譯器在處理未知的
-
窗口的屬性設(shè)置:
-
Title="MainWindow"
:設(shè)置窗口的標題為 “MainWindow”。 -
Height="450"
和Width="800"
:設(shè)置窗口的高度和寬度分別為450和800。
-
布局
所有東西都可以通過屬性來改變
-
StackPanel
StackPanel 主要用于垂直或水平排列元素、在容器的可用尺寸內(nèi)放置有限個元素,元素的 尺寸總和(長/高)不允許超過 StackPanel 的尺寸, 否則超出的部分不可見。
-
WrapPanel
WrapPanel 默認排列方向與 StackPanel 相反、WrapPanel 的 Orientation 默認為 Horizontal。 WrapPanel 具備 StackPanel 的功能基礎(chǔ)上具備在尺寸變更后自動適應(yīng)容器的寬高進行換行換列處理。
-
DockPanel
??渴讲季?/p>
內(nèi)部控件通過DockPanel.Dock 屬性來布局,默認添加 Left。
DockPanel 有一個 LastChildFill 屬性, 該屬性默認為 true, 該屬性作用為, 當容器中的最后一個元素時, 默認該元素填充 DockPanel 所有空間。
-
Grid
Grid 具備分割空間的能力。
RowDefinitions / ColumnDefinitions 用于給 Grid 分配行與列。
Row / Column 來確定控件位置
ColumnSpan / RowSpan來設(shè)置控件長寬
如下來進行分割與分配
尺寸中auto表示跟網(wǎng)格內(nèi)的控件一樣,*表示比例劃分auto剩下的
<Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="37*" /> <RowDefinition Height="138*" /> <RowDefinition Height="175*" /> <RowDefinition Height="175*" /> <RowDefinition Height="175*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="58*" /> <ColumnDefinition Width="58*" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="362*" /> <ColumnDefinition Width="71*" /> </Grid.ColumnDefinitions> <Label Grid.Column="1" Content="Label" Grid.ColumnSpan="1" Grid.RowSpan="3" HorizontalAlignment="Center" Grid.Row="2" VerticalAlignment="Center"/>
控件
-
ContentControl 類
內(nèi)容屬性為 Content,只能設(shè)置一次,但可以嵌套
-
ItemsControl 類
此類控件大多數(shù)屬于顯示列表類的數(shù)據(jù)、設(shè)置數(shù)據(jù)源的方式一般通過 ItemSource 設(shè)置。
-
HeaderedContentControl 類
相對于 ContentControl 來說、這類控件即可設(shè)置 Content, 還有帶標題的 Header。 像比較常見的分組控件 GroupBox、TabControl 子元素 TabItem、它們都是具備標題和內(nèi)容的控件。
-
常用控件
- TextBlock: 用于顯示文本, 不允許編輯的靜態(tài)文本。
- TextBox: 用于輸入/編輯內(nèi)容的控件、作用與 winform 中 TextBox 類似, Text 設(shè)置輸入顯示的內(nèi)容。
- Button: 簡單按鈕、Content 顯示文本、Click 可設(shè)置點擊事件、Command 可設(shè)置后臺的綁定命令。
- ComboBox: 下拉框控件, ItemSource 設(shè)置下拉列表的數(shù)據(jù)源, 也可以顯示設(shè)置。
事件
在MainWindow.xaml里面設(shè)置,用于觸發(fā)函數(shù)
namespace WPF
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();//界面顯示
}
//添加的事件函數(shù)
private void Button_Click(object sender, RoutedEventArgs e)
{
}
}
}
樣式
可設(shè)置樣式
- 字體(FontFamily)
- 字體大小(FontSize)
- 背景顏色(Background)
- 字體顏色(Foreground)
- 邊距(Margin)
- 水平位置(HorizontalAlignment)
- 垂直位置(VerticalAlignment)
全局的在app中的<Application.Resources>中添加
局部的在當前xaml里面添加<Window.Resources>(與grid同級)
<Style x:Key="TextBlockStyle" TargetType="TextBlock">
<Setter Property="Text" Value="TextBlock" />
<Setter Property="Height" Value="30" />
<Setter Property="Width" Value="60" />
<Setter Property="Background" Value="Red" />
</Style>
使用
<TextBlock TextWrapping="Wrap" Style="{StaticResource TextBlockStyle}"/>
<!--這里也可以再修改樣式,優(yōu)先級高于Style-->
觸發(fā)器
一樣是style,在對應(yīng)事件觸發(fā)時執(zhí)行
<Style x:Key="TextBlockStyle" TargetType="TextBlock">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Blue" />
</Trigger>
</Style.Triggers>
</Style>
模板
控件模板
我們在樣式中所能做的修改有限,
于是可以右鍵控件,編輯副本來創(chuàng)建新的控件
如給按鈕添加圓角
在編輯副本后,在生成的副本中,給Border標簽加上CornerRadius="10"
然后設(shè)置按鈕Style="{StaticResource ButtonStyle1}"
數(shù)據(jù)模板
CellTemplate
表格實現(xiàn),利用grid
模板直接放在里,這個表格設(shè)置了三列,并在第四列設(shè)置了兩個按鈕
<DataGrid Name="gd" AutoGenerateColumns="False" CanUserSortColumns="True" CanUserAddRows="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding UserName}" Width="100" Header="學生姓名"/>
<DataGridTextColumn Binding="{Binding ClassName}" Width="100" Header="班級名稱"/>
<DataGridTextColumn Binding="{Binding Address}" Width="200" Header="地址"/>
<DataGridTemplateColumn Header="操作" Width="100" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Left">
<Button Content="編輯"/>
<Button Margin="8 0 0 0" Content="刪除" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
綁定數(shù)據(jù),在InitializeComponent();后面
public class Student
{
public string UserName { get; set; }
public string ClassName { get; set; }
public string Address { get; set; }
}
List<Student> students = new List<Student>();
students.Add(new Student() { UserName = "小王", ClassName = "高二三班", Address = "廣州市" });
students.Add(new Student() { UserName = "小李", ClassName = "高三六班", Address = "清遠市" });
students.Add(new Student() { UserName = "小張", ClassName = "高一一班", Address = "深圳市" });
students.Add(new Student() { UserName = "小黑", ClassName = "高一三班", Address = "贛州市" });
gd.ItemsSource = students;
ItemTemplate
用來綁定控件內(nèi)容,如下
<Window.Resources>
<DataTemplate x:Key="comTemplate">
<StackPanel Orientation="Horizontal" Margin="5,0">
<Border Width="10" Height="10" Background="{Binding Code}"/>
<TextBlock Text="{Binding Code}" Margin="5,0"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<ComboBox Name="cob" Width="120" Height="30" ItemTemplate="{StaticResource comTemplate}"/>
<ListBox Name="lib" Width="120" Height="100" Margin="5,0" ItemTemplate="{StaticResource comTemplate}"/>
</StackPanel>
</Grid>
綁定數(shù)據(jù)
public class Color
{
public string? Code { get; set; }
}
List<Color> ColorList = new List<Color>();
ColorList.Add(new Color() { Code = "#FF8C00" });
ColorList.Add(new Color() { Code = "#FF7F50" });
ColorList.Add(new Color() { Code = "#FF6EB4" });
ColorList.Add(new Color() { Code = "#FF4500" });
ColorList.Add(new Color() { Code = "#FF3030" });
ColorList.Add(new Color() { Code = "#CD5B45" });
cob.ItemsSource = ColorList;
lib.ItemsSource = ColorList;
ContentTemplate
用得很少,不提了
綁定
前端顯示后后端數(shù)據(jù)的關(guān)聯(lián)
綁定控件
通過給控件取名,然后根據(jù)名字將text的值綁定為上面slider控件的value
<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
<Slider Name="slider" Width="200" />
<TextBlock Text="{Binding ElementName=slider, Path=Value}" HorizontalAlignment="Center" />
</StackPanel>
綁定模式
如下進行設(shè)置
<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
<Slider Name="slider" Width="200" />
<TextBox Width="200" Text="{Binding ElementName=slider, Path=Value, Mode=OneWay}" HorizontalAlignment="Center" />
</StackPanel>
常用模式
OneWay : 單向綁定,綁定對象會決定自己
TwoWay : 雙向綁定,下面輸入后tab即可顯示
OneTime : 只綁定第一次的值,這里直接綁定啟動的值了
OneWayToSource : 與OneTime一樣,對象相反
Default : 默認單項或雙向
綁定數(shù)據(jù)
Source
<Window.Resources>
<TextBox x:Key="txt1">ABC</TextBox>
</Window.Resources>
<Grid>
<TextBox Text="{Binding Source={StaticResource txt1}, Path=Text}" />
</Grid>
RelativeSource
查看相關(guān)標簽的數(shù)據(jù)
<StackPanel Width="20">
<StackPanel Width="60">
<TextBlock Text="{Binding Path=Width,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type StackPanel}}}" />
</StackPanel>
</StackPanel>
DataContext
與代碼數(shù)據(jù)綁定
<Grid>
<DataGrid Grid.Row="1" ItemsSource="{Binding Students}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}" Header="名稱" />
<DataGridTextColumn Binding="{Binding Age}" Header="年齡" />
<DataGridTextColumn Binding="{Binding Sex}" Header="性別" />
</DataGrid.Columns>
</DataGrid>
</Grid>
綁定
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
PageModel page = new PageModel();
page.Students = new List<Student>();
page.Students.Add(new Student() { Name = "張三", Age = "18", Sex = "男" });
page.Students.Add(new Student() { Name = "李四", Age = "19", Sex = "男" });
page.Students.Add(new Student() { Name = "王二", Age = "20", Sex = "女" });
this.DataContext = page;
}
}
public class PageModel
{
public List<Student> ?Students { get; set; }
}
public class Student
{
public string? Name { get; set; }
public string? Age { get; set; }
public string? Sex { get; set; }
}
MVVM
在開發(fā)大型項目時收益高
我們的頁面設(shè)計xaml和我們的數(shù)據(jù)分開,利用框架,可以二者完全分離
在MainWindow.xaml中設(shè)置界面和綁定(數(shù)據(jù),函數(shù)(函數(shù)參數(shù)))
在MainViewModel.cs中來實現(xiàn)數(shù)據(jù)的處理和提供函數(shù)接口,(替換原生在MainWindow.xaml.cs里來設(shè)置響應(yīng))
讓前后端的工作分開,專心處理一種邏輯
有很多MVVM框架,這里使用prism
實戰(zhàn)
把頁面劃分為區(qū)域,用區(qū)域便于設(shè)置
安裝框架 : 項目->管理NuGet程序包->Prism.DryIoc(Prism Dry Inversion of Control)
NuGet(發(fā)音為"New Get")是一個用于.NET平臺的包管理系統(tǒng)
使用Prism
對App.xaml進行操作
cs
修改繼承并重寫方法
public partial class App : PrismApplication
{
protected override Window CreateShell()
{//初始頁
return Container.Resolve<MainWindow>();
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{//用于注冊要實現(xiàn)的頁面
}
}
xaml
添加命名空間prism并刪除StartupUri
<prism:PrismApplication x:Class="WPF.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPF"
xmlns:prism ="http://prismlibrary.com/">
<Application.Resources>
</Application.Resources>
</prism:PrismApplication>
項目模板
擴展->管理擴展->Prism Template Pack->然后新建該模板的項目,就會自動配置好上面使用框架的內(nèi)容
框架自動生成兩個文件夾 :
Views用來存放我們的界面
ViewModels來存放我們的指令
只要放在這兩個文件夾下就會自動關(guān)聯(lián),不需要麻煩的指定
然后就是了解region,在框架中,界面通過region來控制.
在MainWindow.xaml
代碼中定義region
<ContentControl prism:RegionManager.RegionName="ContentRegion" Grid.ColumnSpan="2" />
如果需要顯示,在MainWindowViewModel.cs
中注冊區(qū)域,
下面將顯示ViewA這個界面
public class MainWindowViewModel : BindableBase
{
private IRegionManager regionManager;
public MainWindowViewModel(IRegionManager regionManager)
{
this.regionManager = regionManager;
regionManager.RegisterViewWithRegion("ContentRegion", typeof(ViewA));
}
}
模塊
創(chuàng)建 -> 模塊
模塊的ModuleAModule.cs
文件
public class ModuleAModule : IModule
{
public void OnInitialized(IContainerProvider containerProvider)
{
var regionManager = containerProvider.Resolve<IRegionManager>();
regionManager.RegisterViewWithRegion("ContentRegion", typeof(ViewA));
}
public void RegisterTypes(IContainerRegistry containerRegistry)
{
}
}
然后主程序的App
public partial class App : PrismApplication
{
protected override Window CreateShell()
{
return Container.Resolve<MainWindow>();
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
}
protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
{
moduleCatalog.AddModule<ModuleA.ModuleAModule>();
}
}
MAUI
需要下載.NET Multi_platform App UI開發(fā)
新建->.NET MAUI->.net6.0->運行
因為跨平臺,沒辦法像WPF那樣實時渲染,得自己運行來看效果,不過確實方便
因為跨平臺,開發(fā)成本低,運行成本高
示例程序計算器源碼
項目結(jié)構(gòu)
- App是MAUI應(yīng)用的入口點,它們定義了一個App類,繼承自Application類;App.xaml是用
XAML語言聲明App類的屬性和資源,如主題顏色,字體大小等;App.xaml.cs是用C#語言
編寫App類的邏輯,如初始化應(yīng)用,設(shè)置主窗口,處理生命周期事件等。 - AppShell是MAUI應(yīng)用的導航框架,它們定義了一個AppShell類,繼承自Shell類;
AppShell.xaml是用XAML語言聲明AppShell類的內(nèi)容和結(jié)構(gòu),如導航菜單,標簽頁,飛出
頁等;AppShell.xaml.cs是用C#語言編寫AppShell類的邏輯,如注冊路由,處理導航事件
等。 - MainPage是MAUI應(yīng)用的主頁面,它們定義了一個MainPage類,繼承自ContentPage類;
MainPage.xaml是用XAML語言聲明MainPage類的用戶界面,如控件,布局,樣式等;
MainPage.xaml.cs是用C#語言編寫MainPage類的邏輯,如事件處理,數(shù)據(jù)綁定,頁面生命
周期等。 - MauiProgram.cs是應(yīng)用的跨平臺入口點,它用來配置和啟動應(yīng)用。模板啟動代碼指向了
App.xaml文件中定義的App類。
安卓環(huán)境
用虛擬機或真機
- 模擬器是一種虛擬設(shè)備,它可以在你的開發(fā)機上模擬不同平臺的設(shè)備,如Android手機或iOS手機。配置方式請參考:管理虛擬設(shè)備
- 真機是一種實體設(shè)備,它可以通過USB或無線連接到你的開發(fā)機上,如Android手機或iOS手機。配置方式請參考:設(shè)置設(shè)備進行開發(fā)
安全
對所有輸入一定要謹慎,(正則匹配),防止胡亂的輸入讓程序崩潰,即提高魯棒性文章來源:http://www.zghlxwxcb.cn/news/detail-775549.html
如在計算器中輸入1***************1*
文章來源地址http://www.zghlxwxcb.cn/news/detail-775549.html
到了這里,關(guān)于基于C#語言的GUI開發(fā),主要介紹WPF框架的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!