Search code examples
c#wpfwrappanel

Find actual position of an element in WrapPanel


I have a WrapPanel and three buttons on it. the third button in WrapPanel is in second line. I want to find the real psotion of button4.

<WrapPanel Height="100" Width="200">
   <Button Content="Button" Height="23" Name="button2" Width="75" />
   <Button Content="Button" Height="23" Name="button3" Width="75" />
   <Button Content="Button" Height="23" Name="button4" Width="75" />
</WrapPanel>

I use this code but it is 0 because margin is 0.

int top = button4.Margin.Top //I want in this case top become 23 but it is 0.

Solution

  • To find the button position in the WrapPanel, you should use TransformToAncestor (msnd)

     Point currentPoint = button4.TransformToAncestor(myWrapPanel).Transform(new Point(0, 0));
    

    Where myWrapPanel is your WrapPanel.