Live Chat Icon For mobile
Live Chat Icon

WPF FAQ - Buttons

Find answers for the most frequently asked questions
Expand All Collapse All

‘Subclass Button’ and adding a custom ‘Paint’ event handler lets you do this.

[C#]
 
public class CustomButton : Button
{
  public CustomButton()
  {
    Paint += new PaintEventHandler( ButtonPaint );
  }

  private void ButtonPaint( object sender, PaintEventArgs e )
  {
    Pen pen = new Pen( Color.Red );
    pen.Width = 8;
    e.Graphics.DrawLine( pen, 7, 4, 7, Height - 4 );
    pen.Width = 1;
    e.Graphics.DrawEllipse( pen, Width - 16 , 6, 8, 8 );
  }
}
Permalink

The button’s shape can be changed to any shape by applying the control template to a button. The following code snippet is used to change the shape of a button to an ellipse.

[XAML]

<ControlTemplate x:Key='Temp1' TargetType='{x:Type Button}'>
<Grid>
<Ellipse x:Name='Ell' Width='{TemplateBinding Width}' Height='50'>
<Ellipse.Fill>
            <LinearGradientBrush StartPoint='0,0.5' EndPoint='1,0.5'>
            <GradientStop Offset='0.3' Color='YellowGreen'/>
            <GradientStop Offset='1' Color='Green'/>
            </LinearGradientBrush>
            </Ellipse.Fill>
</Ellipse>
<Viewbox>
<ContentControl Margin='10' Content='{TemplateBinding Content}' FontSize='11' HorizontalContentAlignment='Center' Foreground='AntiqueWhite'/>
            </Viewbox>
</Grid>
</ControlTemplate>

<Button Name='Button1' Template='{StaticResource Temp1}'  Height='50' Width='80'>Templated Button</Button>

Permalink

This can be done with the following piece of code.

[C#]
 
public class RepeatButton : Button
{  
 private Timer timer1;
  public int Interval
  {
    get { return Timer.Interval; }
    set { Timer.Interval = value; }
  }

  private Timer Timer
  {
    get
    {
      if ( timer1 == null )
      {
        // create and setup the timer
        timer1 = new Timer();
        timer1.Tick += new EventHandler( OnTimer );
        timer1.Enabled = false;
      }
      return timer1;
    }
  }

  protected override void OnMouseDown( MouseEventArgs me )
  {
    base.OnMouseDown( me );
    Timer.Enabled = true; // turn on the timer
  }

  protected override void OnMouseUp( MouseEventArgs me )
  {
    Timer.Enabled = false; // turn off the timer
    base.OnMouseUp( me );
  }

  private void OnTimer( object sender, EventArgs e )
  {
    OnClick( EventArgs.Empty ); // fire off a click on each timer tick
  }
}
Permalink

Share with

Couldn't find the FAQs you're looking for?

Please submit your question and answer.