Search code examples
c#wpfexpander

How to find the center of a expanding expander


OK this has me puzzled and it should be simple

I have this code

private void Expander_Expanded(object sender, RoutedEventArgs e)
{
    var expand = e.OriginalSource as Expander;
    if (expand != null)
    {
        var layer = sender as LayerBase;
        var middle = expand.TranslatePoint(new Point(), layer) + new Vector(expand.ActualWidth/2,expand.ActualHeight/2);
        Location.Centre = layer.ScreenToGeoPoint(middle);
        e.Handled = true;
    }
}

This is what the code is supposed to do,

  • Locate the Screen point in the centre of the control
  • locate the Geographic point that relates to that screen point
  • recentre the map to those coordinates

this is so as to ensure the expander is in the centre of the displayed map, with out moving the expander relative to the map (ie so the top left corner is still in the correct geographic location)

the code itself is functioning however, ActualHeight and ActualWidth are returning the size of the collapsed expander, which is throwing off the centre point by a large margin, I'm assuming that this because the Expanded event is firing before the control redraws. so how do I capture that expanded has changed after the visual tree redraws?


Solution

  • private async void Expander_Expanded(object sender, RoutedEventArgs e)
    {
        var expand = e.OriginalSource as Expander;
        if (expand != null)
        {
            var layer = sender as LayerBase;
            // magic
            await Dispatcher.InvokeAsync( ( ) => { } );
            expand.UpdateLayout();
            var middle = expand.TranslatePoint(new Point(), layer) + new Vector(expand.ActualWidth/2,expand.ActualHeight/2);
            Location.Centre = layer.ScreenToGeoPoint(middle);
            e.Handled = true;
        }
    }
    

    This works :)