2017-08-24 100 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的样式不存在,并且该控件没有为文本或其他内容的去向定义占位符。如果你想要这样做,你最好用一个控件模板来定义这种风格,并且可以放在那里的视觉效果中。