Search code examples
c#wpfbuttonuielement

Custom button not rendering correctly


I've got a custom class for a button with a circular image as I'll be using it multiple times through my program. I thought it'd be pretty simple of creating class, inheriting from Button and slapping my setup into a constructor, but when I'm running the program the buttons are massive and plain (no image or text). Here's my class:

public class ImageButton : Button
{
    public Button Button;

    public ImageButton(string filename) : this(HorizontalAlignment.Center, VerticalAlignment.Center, filename)
    { }

    public ImageButton(HorizontalAlignment hAlignment, VerticalAlignment vAlignment, string filename)
    {
        Button = new Button
        {
            Width = 35,
            Height = 35,
            Background = Brushes.Transparent,
            HorizontalAlignment = hAlignment,
            BorderBrush = Brushes.Transparent,
            VerticalAlignment = vAlignment,
            Content = new Image
            {
                Source = new BitmapImage(new Uri("pack://application:,,,/Resources/" + filename))
            }
        };
    }

}

And here's my implementation of one of the instances

private void SetupHeaders(Grid resultGrid)
{
    RowDefinition backbtn = new RowDefinition();
    backbtn.Height = new GridLength(0.2, GridUnitType.Star);
    resultGrid.RowDefinitions.Add(backbtn);
    btn_Return = new ImageButton(HorizontalAlignment.Left, VerticalAlignment.Top, "returnicon.png");
    Grid.SetRow(btn_Return, 0);
    Grid.SetColumn(btn_Return, 0);
    resultGrid.Children.Add(btn_Return);

}

with btn_Return being defined at the top of the class as simply

ImageButton btn_Return;

Here's an image of one of the buttons. enter image description here


Solution

  • In you constructor you inititalize a Button with you properties and then assign it to a property. You never actually use the initialized button. You are always using ImageButton which is nothing more than an inherited button therefore you get the default behavior.

    You have to change your constructor.

    public ImageButton(HorizontalAlignment hAlignment, VerticalAlignment vAlignment, string filename)
    {
        Width = 35;
        Height = 35;
        Background = Brushes.Transparent;
        HorizontalAlignment = hAlignment;
        BorderBrush = Brushes.Transparent;
        VerticalAlignment = vAlignment;
        Content = new Image
        {
            Source = new BitmapImage(new Uri("pack://application:,,,/Resources/" + filename))
        };
    }