I am trying to get the position of user control via TransformToVisual method using this line of code:
this.TransformToVisual(ParentElement).Transform(new Point());
If the control is defined in XAML, coordinates are all right. But now I want to define controls dynamicaly like this:
stackPanel.Children.Add(new Control());
The coordinates are shifted and the TransformToVisual method is ignoring margins and aligns (returns top-left corner of stackpanel).
The XAML hierarchy is following:
<Grid x:Name="ParentElement">
<StackPanel>
<StackPanel>
<Border>
<StackPanel>
<TextBlock />
<StackPanel x:Name="stackPanel" />
</StackPanel>
</Border>
</StackPanel>
</StackPanel>
</Grid>
So my question is: is there any way to get the coordinates properly again?
Thanks, kwitee
I was able to fix the issue myself:
If I call UpdateLayout() method before calling TransformToVisual(), coordinates are no longer bad. There was some other minor issue with ActualWidth and height properties, which were returned as zeros. I fixed that by calling these properties in Dispatcher.BeginInvoke delegate.