在WPF中,事件处理机制与传统的WinForms有很大的不同。WPF提供了更加灵活和强大的事件处理方式,包括XAML声明式事件绑定和代码后置事件处理两种主要方式。
XML<Window x:Class="AppEvent.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:AppEvent"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<StackPanel>
<!-- 基本事件绑定 -->
<Button Content="点击我" Click="Button_Click" Margin="10"/>
<!-- 带参数的事件绑定 -->
<Button Content="带参数的按钮"
Click="Button_Click_WithParameter"
Tag="自定义参数"
Margin="10"/>
<!-- 多个事件的绑定 -->
<TextBox Text="输入些内容"
TextChanged="TextBox_TextChanged"
KeyDown="TextBox_KeyDown"
Margin="10"/>
</StackPanel>
</Window>
在WPF开发中,XAML的集合语法是一个非常重要的概念。它允许我们以声明式的方式定义和初始化各种集合类型的属性。本文将详细介绍XAML中的集合语法使用方法。
XAML中的集合主要有两种表示方法:
text<StackPanel> <!-- 使用标签语法添加子元素 --> <StackPanel.Children> <Button Content="按钮1"/> <Button Content="按钮2"/> <TextBlock Text="文本块"/> </StackPanel.Children> </StackPanel>

属性元素语法(Property Element Syntax)是XAML中一种特殊的语法形式,它允许我们以XML元素的形式来设置对象的属性,而不是使用传统的属性语法。这种语法特别适用于:
属性元素语法的基本格式为:
text<对象类型> <对象类型.属性名> 属性值 </对象类型.属性名> </对象类型>
个人觉得这一套逻辑其实比html 要好。
以下两种写法是等价的:
text<!-- 传统属性语法 --> <Button Background="Red" Content="点击我"/> <!-- 属性元素语法 --> <Button Content="点击我"> <Button.Background> <SolidColorBrush Color="Red"/> </Button.Background> </Button>

标记扩展是XAML中一种特殊的语法机制,允许在属性赋值时动态计算或引用值,而不仅仅是使用简单的文本字符串。它们提供了一种在XAML中灵活处理值的方式,可以实现复杂的赋值逻辑。
StaticResource用于引用已经定义的资源,通常在资源字典中。
text<Window.Resources> <SolidColorBrush x:Key="PrimaryBrush" Color="Blue"/> </Window.Resources> <Grid Background="{StaticResource PrimaryBrush}"> <!-- 使用静态资源 --> </Grid>

与StaticResource类似,但会在运行时动态更新资源。
text<Window.Resources> <SolidColorBrush x:Key="ThemeBrush" Color="Green"/> </Window.Resources> <Button Background="{DynamicResource ThemeBrush}"> 动态资源按钮 </Button>
XAML命名空间是用于在XAML文件中定义和区分不同类型和功能的标识符。它们类似于XML命名空间,帮助解析器识别和解析XAML文档中的元素和属性。命名空间在XAML中是必需的,因为它们确保了元素和属性的唯一性,避免了命名冲突。
XMLxmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Button、Grid、StackPanel等。