Search code examples
c#wpfarrangeoverride

Override measure/arrange will hide button control


I have the following

public class MatrixButton : Button
{
  public MatrixButton()
  {
    Height = 20;
    Width = 44;
    Content = "foo";
  }

  protected override Size MeasureOverride(Size constraint)
  {
    var measureOverride = new Size(44, 20);
    return measureOverride;
  }

  protected override Size ArrangeOverride(Size arrangeBounds)
  {
    var arrangeOverride = new Size(44, 20);
    return arrangeOverride;
  }
}

Now I put that button just in an empty window like that:

public partial class MainWindow : Window
{
  public MainWindow()
  {
    InitializeComponent();
    Content = new MatrixButton();

  }
}

For some reason that button is not visible in the window. Does anyone know why? If I remove the overrides the button is displayed correct ofcourse...

edit: the reason is that the button is integrated in a complex layout where there are a lot of them and the layout pass is consuming a lot of time but the button's size will be always the same


Solution

  • Even if you want to contrain the size, you still should call the base methods for the child elements of the Button to be measured and arranged as expected:

    protected override Size MeasureOverride(Size constraint)
    {
        var measureOverride = new Size(44, 20);
        base.MeasureOverride(measureOverride);
        return measureOverride;
    }
    
    protected override Size ArrangeOverride(Size arrangeBounds)
    {
        var arrangeOverride = new Size(44, 20);
        base.ArrangeOverride(arrangeOverride);
        return arrangeOverride;
    }