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}
),這是其核心優勢。