網頁 position:absolute 下的 left/top/z-index 與 WPF Canvas 絕對定位異曲同工。原代碼混用 Canvas.SetLeft/SetTop/SetValue(ZIndexProperty),風格不一、可讀性差。
public double Left
{
get => (double)GetValue(Canvas.LeftProperty);
set => SetValue(Canvas.LeftProperty, value);
}
public double Top
{
get => (double)GetValue(Canvas.TopProperty);
set => SetValue(Canvas.TopProperty, value);
}
public int ZIndex
{
get => (int)GetValue(Canvas.ZIndexProperty);
set => SetValue(Canvas.ZIndexProperty, value);
}
重構前 (風格混亂):
MapSurface.Width = 1750;
MapSurface.Height = 1440;
MapSurface.Source = ...;
Carrier.Children.Add(MapSurface);
Canvas.SetLeft(MapSurface, -320);
Canvas.SetTop(MapSurface, -200);
MapSurface.SetValue(Canvas.ZIndexProperty, -1);
重構後 (統一屬性賦值,優雅易讀):
MapSurface.Width = 1750;
MapSurface.Height = 1440;
MapSurface.Source = ...;
MapSurface.Left = -320;
MapSurface.Top = -200;
MapSurface.ZIndex = -1;
Carrier.Children.Add(MapSurface);
書寫統一、語義清晰、維護輕鬆 — 重構重要手法之一。