WPF: How to Calculate the Width/Height a Control would like to draw into

Basically I wanted to see if the area I have been given to draw my controls into is too small, i.e. the controls will end up being clipped.
If you know the area is too small to contain your controls then you can do something about it. In this case I have a button that either expands or collapses the area (hence the use of a GridSplitter).
My WPF XAML setup is as follows (bits removed to keep this simple):
<UserControl ....>
  <Grid Background="AliceBlue" Name="TopGrid">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="12*" Name="Graph" />
        <ColumnDefinition Width="5" Name="GridSplitter" />
        <ColumnDefinition Width="2*" Name="ManualControlsSplit" />
    </Grid.ColumnDefinitions>

    <Grid Grid.Column="0" Background="AliceBlue"
          HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
    <!-- A Graph and simple controls -->
    </Grid>

    <!--  GRID SPLITTER  -->
    <GridSplitter Grid.Column="1" Width="5"
          HorizontalAlignment="Stretch" Name="Splitter" />
    <Label Grid.Column="1" Content="⁞" Foreground="White" 
          Background="DarkGray"
          VerticalAlignment="Center" FontSize="26" FontWeight="Bold" 
          IsHitTestVisible="False"/>
    <!-- end GRID SPLITTER -->

    <StackPanel Grid.Column="2" Grid.Row="0" Margin="5"
          Name="TemperatureControls">
    <!-- Load of Controls -->
    </StackPanel>
  </Grid>
</UserControl>
To calculate the desired width I use the following code:
// get my UserControl object
var manualControlView = userControl as HeatingController.Views.ManualControlView;

// Query the current width of THIRD column
double actualWidth = manualControlView.ManualControlsSplit.ActualWidth;

// Set up a BIG size (this has to be bigger size than the contents of the
// THIRD column would ever need)
Size size = new Size(400, manualControlView.TopGrid.ActualHeight);

// Ask WPF layout to calculate the Desired size.
manualControlView.TemperatureControls.Measure(size);

double width = manualControlView.TemperatureControls.DesiredSize.Width;
if (actualWidth <= width)
{
   // Too small - do something
}
else
{
   // big enough - do something else.
}
The variable 'width' now contains the value I wanted to calculate.

Comments