WPF常用控件及核心属性
以下是WPF开发中最常用的控件及其关键属性(按功能分类):
基础布局控件
Grid
(网格布局)RowDefinitions
:行定义集合(如Height="Auto"
)ColumnDefinitions
:列定义集合(如Width="*"
)Grid.Row
/Grid.Column
:子元素位置附加属性
StackPanel
(线性布局)Orientation
:排列方向(Horizontal
/Vertical
)
Canvas
(绝对定位)Canvas.Left
/Canvas.Top
:子元素坐标附加属性
文本与输入控件
TextBox
(文本框)<TextBox Text="输入内容" Width="200" MaxLength="50" IsReadOnly="False"/>
Text
:文本内容MaxLength
:最大字符数TextWrapping
:换行方式(Wrap
/NoWrap
)
Label
(标签)Content
:显示内容(支持文本或对象)Target
:绑定焦点目标控件
RichTextBox
(富文本)Document
:流文档对象(支持复杂格式)
选择控件
ComboBox
(下拉框)<ComboBox ItemsSource="{Binding Items}" SelectedItem="{Binding Selected}"/>
ItemsSource
:数据源集合SelectedIndex
:选中项索引IsEditable
:是否可编辑
ListBox
(列表框)SelectedValue
:选中项的值SelectionMode
:选择模式(Single
/Multiple
)
CheckBox
(复选框)IsChecked
:选中状态(True
/False
/Null
三态)Content
:右侧说明文本
RadioButton
(单选按钮)GroupName
:分组名称(同组互斥)IsChecked
:选中状态
交互控件
Button
(按钮)<Button Content="确定" Command="{Binding SubmitCommand}" Click="Button_Click"/>
Command
:绑定命令对象Click
:点击事件
Slider
(滑动条)Minimum
/Maximum
:值范围Value
:当前值TickFrequency
:刻度间隔
ProgressBar
(进度条)Value
:当前进度值IsIndeterminate
:是否显示动画(无确定进度时)
图像与媒体
Image
(图像)<Image Source="/Images/logo.png" Stretch="Uniform"/>
Source
:图像路径(支持URI)Stretch
:拉伸模式(None
/Fill
/Uniform
)
MediaElement
(媒体播放器)Source
:媒体文件路径Play()
/Pause()
:控制方法
数据展示
DataGrid
(数据表格)<DataGrid ItemsSource="{Binding Users}" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTextColumn Header="姓名" Binding="{Binding Name}"/> </DataGrid.Columns> </DataGrid>
ItemsSource
:数据源AutoGenerateColumns
:是否自动生成列
TreeView
(树形视图)ItemsSource
:层级数据源SelectedItem
:选中节点
通用核心属性
所有控件继承自
FrameworkElement
的通用属性:
Width
/Height
:尺寸Margin
/Padding
:外边距/内边距Visibility
:可见性(Visible
/Collapsed
/Hidden
)Background
/Foreground
:背景/前景色Style
:样式资源引用DataContext
:数据绑定上下文
示例:组合控件布局
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<Label Content="用户名:" Target="{Binding ElementName=txtUser}"/>
<TextBox x:Name="txtUser" Width="150"/>
<Button Content="登录" Margin="10,0"/>
</StackPanel>
<ListBox Grid.Row="1" ItemsSource="{Binding Items}"/>
</Grid>
提示:WPF属性支持数据绑定(如
{Binding Path}
)和资源引用(如{StaticResource Key}
),这是其核心优势。