9-2 【操作】WPF 基础入门
新建一项目
Create a new project - WPF Application (A project for creating a .NET Core WPF Application) - Next - .NET 5.0 (Current) - Create
项目创建完成,VS自动打开 GUI用户界面,格式是 .xaml文件,跟xml差不多,也属于xml文件的类别。
虽然xaml是WPF用户的底层标准,但是VS已帮我们全部封装好了,可以直接拖拽布局界面。
9-3 【理论】XAML页面剖析
MainWindow.xaml代码示例
<Window x:Class="WpfApp.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:WpfApp"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button Height="50" Width="100" Content="CLick me 4" />
<d:Button>
<Button.Height>50</Button.Height>
<Button.Width>100</Button.Width>
<Button.Content>
<TextBlock>Click me 4</TextBlock>
</Button.Content>
</d:Button>
</Grid>
</Window>
上面标红的<Button> 相当于下面的7行代码(当然不能有 d:),因为<Button ……> 的内部属性可以通过“元素嵌套”的方式声明。
<Window ……> 根元素介绍
xmlns 是 xml-namespace 的缩写,用于定义命名空间的。上面看到的是MS系统默认的命名空间,可以使用这个命名空间下的所有UI控件。
比如这里的 Button TextBlock,另外当来源不同的类重名时,也可以通过命名空间区分不同的UI控件。
xmlns 是默认的命名空间,这种不带任何映射参数的命名空间,整个页面只能有一个,一般使用元素最频繁使用的命名空间。
比如这里的 Window Grid Button TextBlock,都来自 xmlns 。
接着,还能看到带有映射前缀的:x 、:d 等的命名空间,这些命名空间都与解析 xaml语言相关,
比如这里的 x:Class 来自 xmlns:x 这个命名空间,它将会指定当前页面所对应的 cs 文件,以及当前页面所对应的类的名称。
比如这里的 xmlns:local代表当前应用的命名空间,即项目名称:WpfApp,而
Title="MainWindow" Height="450" Width="800" 分别定义了视窗的标题、高度和宽度。
mc:Ignorable="d"这个命名空间稍微有点费解,它的名称叫 Ignorable,即可以忽略的,表示在运行过程中可以被忽略的控件,而这些可忽略的控件使用 d: 来引导。即运行时忽略,上面布局中有两个 Button ,运行时,下面的Button不会显示的。
MainWindow.xaml.cs(UI页面逻辑代码)代码示例
……
namespace WpfApp
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var grid = (Grid)this.Content;
Button button = new Button();
button.Height = 50;
button.Width = 100;
Margin = new Thickness(0, 0, 700, 385);
button.Content = "Button !!!";
grid.Children.Add(button);
}
}
}
x:Class="WpfApp.MainWindow" 对应上面的 namespace WpfApp 和 class MainWindow。
构造函数 public MainWindow() 在程序启动时调用。InitializeComponent();帮助完成页面初始化工作(比如初始化标题、字体大小等)。
<


6578

被折叠的 条评论
为什么被折叠?



