NVM
NVM

Reputation: 5552

WPF TextBox recalculate size

When using a wpf textbox without explicit height and width values, and when there is space available to expand, the textbox resizes as you type.

However when I change the border thickness, it does not recalculate it and for very thick borders, part of the text is covered by the border. How do I explicitly precipitate a recalc?

Coincidently I am using a derived custom textbox class so I should know when the border thickness changes.

enter image description here

Upvotes: 3

Views: 1445

Answers (2)

Fredrik Hedblad
Fredrik Hedblad

Reputation: 84684

This bug must be some optimization gone wrong

  • Overriding Metadata for BorderThickness or adding a Dependency Property that affects Measure, Arrange or Render don't help
  • Undocking and Redocking from the parent container had no effect either
  • Even Undocking from the parent container and Redocking into a new container won't help if the space it is given in the new container is exactly the same as the space that it had in the old container

It seems like the size is only re-calculated once Text, Width, Height or available space changes. I looked around with Reflector but things get pretty complex down there so I couldn't find the source for this.

Here is a small workaround that listens to changes in BorderThickness and in the changed event handler, make a small change to the Width and once it is updated, change it right back

public class MyTextBox : TextBox
{
    public MyTextBox()
    {
        DependencyPropertyDescriptor borderThickness
            = DependencyPropertyDescriptor.FromProperty(MyTextBox.BorderThicknessProperty, typeof(MyTextBox));
        borderThickness.AddValueChanged(this, OnBorderThicknessChanged);
    }
    void OnBorderThicknessChanged(object sender, EventArgs e)
    {
        double width = this.Width;
        SizeChangedEventHandler eventHandler = null;
        eventHandler = new SizeChangedEventHandler(delegate
        {
            this.Width = width;
            this.SizeChanged -= eventHandler;
        });
        this.SizeChanged += eventHandler;
        this.Width = this.ActualWidth + 0.00000001;
    }
}

Upvotes: 2

Vlad
Vlad

Reputation: 35594

First of all, this looks like a bug.

If the problem is that dynamic changes of the border thickness are not taken into account, you can perhaps make a workaround by creating a dependency property with AffectsMeasure in FrameworkPropertyMetadata, and bind it to the border thickness. Hope this quirk helps.

If the static setting of the border thickness are not taken into account, you can try to replace the TextBox's default template with your own (correct) version.

Upvotes: 1

Related Questions