WPF: Force a shape to fill area while keeping stroke thickness

Enlarging a shape in WPF is simple enough. But if you want to auto-expand to fill a space, you need to do some work. Using a ViewBox makes the shape expand, but it expands everything including the stroke drawn around the outside of the shape. This tip shows you how to make the shape expand but leave the stroke thickness untouched.

Stating the problem
Here a simple problem. At least, at first glance it seems to be.

Problem statement:

  • Use an Ellipse element.
  • Enforce that it is always circular.
  • Draw a 2 pixel stroke on ellipse.
  • Place an ellipse in any standard WPF panel.
  • Have ellipse expand to fill the host panel (but it must remain circular).
  • The stroke must remain at 2 pixels.

First attempt
This XAML obviously won't work. It's a circle and stroke is the correct thickness, but it doesn't expand to fill the container.

Second attempt
This example is better. By putting the Ellipse inside a Viewbox it expands to fill the space. But if the stroke gets thicker and if the container is not rectangular then the ellipse will not be circular.

Third attempt
What if you bound the Width property on the Ellipse to the ActualWidth of the parent container? That would work, but only if the width and height are the same. Otherwise you end up with a none circular item.

Success on the fourth attempt
The secret to making this work it use a multi binding. Multi-bindings take multiple data sources and passes them through a MultiValueConverter. The binding will pass both the parents ActualWidth and ActualHeight to the binding.

 The converter analyzes both parameters and returns the smaller of the two.

 Here's the successful version.

This was first published in August 2010

There are Comments. Add yours.

TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

Disclaimer: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.