首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

WPF 自訂控件開發完全指南:組合、樣式、模板、UserControl 與 Custom Control 抉擇

     編輯:關於.NET

前言:是否真的需要自訂控件?

WPF 提供強大的組合、樣式、模板機制,許多需求無需寫新控件即可滿足。

三種輕量客製化方式

1. 組合

將現有控件組合成新控件。例:Button 內容放入 StackPanel 含 TextBlock + Polygon 圖示。
優點:簡單、無需代碼、按鈕行為保留。

<Button Height="50" Width="50">
  <StackPanel>
    <TextBlock>Play</TextBlock>
    <Polygon Points="0,0 0,26 17,13" Fill="Black"/>
  </StackPanel>
</Button>

2. 樣式

只改外觀屬性(如邊框顏色)。可建立具名樣式或隱式樣式 (無 x:Key) 套用所有同類型控件。

<Style TargetType="Button" x:Key="RedButton">
  <Setter Property="BorderBrush" Value="Red"/>
</Style>
<Button Style="{StaticResource RedButton}" .../>

3. 模板

完全重定義控件視覺樹。透過 ControlTemplate 替換預設外觀,支援 TemplateBinding 綁定控件屬性 (Width/Height 等)。

<Style TargetType="{x:Type Button}" x:Key="PlayButton">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type Button}">
        <Grid>
          <Ellipse Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" .../>
          <Polygon Points="18,12 18,38 35,25" Fill="Black"/>
        </Grid>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

決定撰寫控件時:UserControl vs Custom Control

特性UserControlCustom Control
開發模式類似頁面/視窗開發,XAML + Code-behind純代碼繼承 Control,外觀由 generic.xaml 定義
適用場景組合現有元件、無需複雜模板/主題需完整模板/主題支援、可調整大小、作為容器
遷移難度易遷移至 Custom Control—

不確定時先用 UserControl,遇限制再轉 Custom Control。

UserControl 實作範例:PlayButton

  1. 加入「User Control (WPF)」,XAML 根標籤為 UserControl。
  2. 撰寫視覺樹 (Ellipse + Path 圖示)。
  3. 加入 DependencyProperty (IconColor, MediaPlayer) 支援綁定/動畫。
  4. 處理 MouseLeftButtonUp 切換播放/暫停圖示並控制 MediaElement。
  5. 主視窗引用 CLR 命名空間 xmlns:cust="clr-namespace:CustomWPF" 使用 <cust:PlayButton/>。

Custom Control 進階:MediaButton

  1. 加入「Custom Control (WPF)」,產生類別檔與 Themes/generic.xaml。
  2. 將視覺樹移入 ControlTemplate,用 TemplateBinding 綁寬高。
  3. 用 VisualBrush 讓圖示隨按鈕縮放。
  4. 定義 Icon DependencyProperty (Enum),在模板中用 Trigger 切換 Path Data。
  5. 覆寫 OnMouseLeftButtonUp 處理點擊邏輯。
  6. 繼承 Control 或更基礎類別 (FrameworkElement, Panel) 視需求而定。

總結

  • 優先用組合/樣式/模板客製化現有控件。
  • 需自訂行為時,UserControl 開發最快;需主題化、可縮放、容器化時改用 Custom Control。
  • WPF 罕見需要寫 Custom Control,僅在真正需要自訂行為時才深入。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved