2017-08-24 98 views
-1

我想用類,而不是XAML風格如何使用

此代碼工作的WinForms應用創建圓形按鈕類,我怎樣才能將其轉換爲WPF代碼創建WPF圓角按鈕?

public class RoundButton : Button 
    { 
     protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) 
     { 
      GraphicsPath grPath = new GraphicsPath(); 
      grPath.AddEllipse(0, 0, ClientSize.Width, ClientSize.Height); 
      this.Region = new System.Drawing.Region(grPath); 
      base.OnPaint(e); 
     } 
    } 
+0

難道那種打敗XAML的整個目的?如果你使用的是WPF,你應該做[類似於這個](https://stackoverflow.com/questions/2601604/wpf-user-control-round-corners-programmatically)。 – Sach

回答

1

假設你有一個真的很好的理由這樣做(例如,如果你真的想自定義繪製像畫圖或類似的更復雜的場景),你可以這樣做:

public class RoundButton : Button 
{ 
    public RoundButton() 
    { 
     DefaultStyleKey = typeof(RoundButton); 
    } 

    protected override void OnRender(DrawingContext dc) 
    { 
     double radius = 10; 
     double borderThickness = 1; // Could get this value from any of the this.BorderThickness values 

     dc.DrawRoundedRectangle(Background, new Pen(BorderBrush, borderThickness), new Rect(0, 0, Width, Height), radius, radius); 
    } 
} 

但我真的很建議在這種情況下改用XAML路線。自定義繪圖根本沒有意義。

例如,上述代碼的一個顯而易見的問題是,要使其工作,必須禁用默認按鈕樣式,否則將在繪圖頂部繪製一個按鈕。

在這種情況下,RoundButton的樣式不存在,並且該控件沒有爲文本或其他內容的去向定義佔位符。如果你想要這樣做,你最好用一個控件模板來定義這種風格,並且可以放在那裏的視覺效果中。