4

I'm working on some layout stuff with XAML/C# and for certain reasons I am unable to use the SizeToContent="Width" option however I would like to simulate it in certain situations. I have a user control sitting inside of an expander and I would like to be able to get the ActualWidth of that user control so that when the expander is expanded I can increase the size of the GridColumn and window accordingly. Because the Expander starts off as IsExpanded="False" the ActualWidth property reads as 0.0. Is there any way I can get the ActualWidth of the user control as if it were fully visible and SizeToContent="Width" were in effect?

I've been trying desperately to figure out how to calculate this width without hardcoding the actual value. DesiredSize.Width and RenderedSize.Width also both return 0.0 when the expander is collapsed

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Jesse Carter
  • 20,062
  • 7
  • 64
  • 101
  • If you have `INotifyPropertyChanged` can you just attach a `DataTrigger` and bind it to `ActualWidth` so when the binding is updated then so is your property? Entered as a comment because unfortunately dont have time to test but seems a legit option. – Chris W. May 03 '13 at 15:07
  • @ChrisW. I'll keep this suggestion in mind but I'm not sure that its the approach thats right for this situation – Jesse Carter May 03 '13 at 15:19

1 Answers1

2

I believe that if you run a Measure & Arrange pass, passing in an infinite Size, you'll be able to get the DesiredSize.

var infiniteSize = new Size(double.PositiveInfinity, double.PositiveInfinity);
control.Measure(infiniteSize);

control.Arrange(new Rect(infiniteSize));

correction:

As mentioned in the comments, just calling Measure() with infinite Size does the trick; do not use Arrange().

Community
  • 1
  • 1
Jay
  • 56,361
  • 10
  • 99
  • 123
  • Throws System.InvalidOperationException: Cannot call arrange on a UIElement with infinite size or NaN – Jesse Carter May 03 '13 at 15:36
  • Jay, this worked fine without needing a call to Arrange(). After the Measure I was able to pull out the fully expanded width and height from the DesiredSize property – Jesse Carter May 03 '13 at 15:44