<Canvas Width="200" Height="180" VerticalAlignment="Center">
<Ellipse Canvas.Left="10" Canvas.Top="10" Width="160" Height="160" Fill="Yellow" Stroke="Black"/>
<Ellipse Canvas.Left="45" Canvas.Top="50" Width="25" Height="30" Fill="Black"/> <!-- 左眼 -->
<Ellipse Canvas.Left="110" Canvas.Top="50" Width="25" Height="30" Fill="Black"/> <!-- 右眼 -->
<Path Data="M 50,100 A 30,30 0 0 0 130,100" Stroke="Black"/> <!-- 嘴巴:弧線 -->
</Canvas>
Path.Data 使用微型語法:M (Move)、A (Arc: size, rotationAngle, isLargeArc, sweepDirection, endPoint)。
<Label Content="{Binding TaskDate, StringFormat='yyyy-MM-dd'}" />
直接在綁定中指定格式,無需後台轉換器。
<ControlTemplate.Triggers>
<Trigger Property="Button.IsPressed" Value="True">
<Setter Property="RenderTransform">
<Setter.Value><ScaleTransform ScaleX="0.9" ScaleY="0.9"/></Setter.Value>
</Setter>
<Setter Property="RenderTransformOrigin" Value="0.5,0.5"/>
</Trigger>
</ControlTemplate.Triggers>
RenderTransformOrigin="0.5,0.5" 以中心點縮放,避免位移。
IsOpen 控制顯隱,預設不自動顯示StaysOpen="True" (預設) 需手動關閉;False 點擊外部自動關閉PlacementTarget + Placement 相對元素定位 (如下方彈出)PopupAnimation 開啟動畫PlacementTarget="{Binding ElementName=button1}"
Placement="Bottom"
<Popup PopupAnimation="Fade" Placement="Center" Name="_pupup"><Button>Hello</Button></Popup>
| 特性 | RenderTransform | LayoutTransform |
|---|---|---|
| 套用時機 | 版面配置完成後、渲染前 | 版面配置期間 |
| 影響佈局 | 否 (元素佔用空間不變) | 是 (父容器重新計算空間) |
| 效能 | 較好 (不觸發 Measure/Arrange) | 較差 (觸發完整佈局) |
| 典型用途 | 動畫、旋轉、縮放、傾斜視覺效果 | 需改變元素佔用空間的縮放/旋轉 |
<!-- RenderTransform:按鈕重疊,StackPanel 尺寸不變 -->
<StackPanel Background="Gainsboro" Width="200" Height="80" Orientation="Horizontal">
<Button Width="75" Content="15"><Button.RenderTransform><RotateTransform Angle="15"/></Button.RenderTransform></Button>
<Button Width="75" Content="45"><Button.RenderTransform><RotateTransform Angle="45"/></Button.RenderTransform></Button>
<Button Width="75" Content="65"><Button.RenderTransform><RotateTransform Angle="65"/></Button.RenderTransform></Button>
</StackPanel>
結果:按鈕視覺旋轉但佔用原矩形區域,發生重疊。
<!-- LayoutTransform:StackPanel 自動擴大容納旋轉後按鈕 -->
<StackPanel Background="Gainsboro" Width="250" Height="80" Orientation="Horizontal">
<Button Width="75" Content="15"><Button.LayoutTransform><RotateTransform Angle="15"/></Button.LayoutTransform></Button>
<Button Width="75" Content="45"><Button.LayoutTransform><RotateTransform Angle="45"/></Button.LayoutTransform></Button>
<Button Width="75" Content="65"><Button.LayoutTransform><RotateTransform Angle="65"/></Button.LayoutTransform></Button>
</StackPanel>
結果:StackPanel 高度自動增加,按鈕完整顯示無重疊。
這五個小技巧涵蓋 WPF 核心概念:Canvas 絕對定位繪圖、綁定 StringFormat、ControlTemplate.Trigger 互動回饋、Popup 浮動介面、Transform 兩種模式的佈局影響。掌握它們能快速構建豐富的 WPF 介面原型。