Home > Software engineering >  How can I get the coordinates of an element within a WrapPanel?
How can I get the coordinates of an element within a WrapPanel?

Time:10-31

How can i get the cordinates of an element inside the WrapPanel? I have already tried with myElementInsidenList.TransformToAncestor(rootView).Transform(new Point(0, 0)) but isn't working.

            <ScrollViewer x:Name="myScrollViewer" Background="#2B2B2B" VerticalScrollBarVisibility="Auto">
                <ScrollViewer.Template>
                    <ControlTemplate TargetType="ScrollViewer">
                        <Border CornerRadius="12" Background="{TemplateBinding Background}">
                            <ContentPresenter VerticalAlignment="Top" HorizontalAlignment="Left" />
                        </Border>
                    </ControlTemplate>
                </ScrollViewer.Template>
                <WrapPanel x:Name="nList" VerticalAlignment="Top" />
            </ScrollViewer>

More context

CodePudding user response:

You must wait before the Visual element is rendered. Otherwise there is no position to retrieve.

Also note that your doAnimationAndAddValue() method must return a Task instead of void, if it is an async method that is not an event handler.

Simply listen to the FrameworkElement.Loaded event:

async Task doAnimationAndAddValue()
{
  TextBox targetInput = CloneXaml(cloneInputForAnimation);
  nList.Children.Add(targetInput);
  targetInput.Loaded  = OnTargetInputLoaded;
}

private void OnTargetInputLoaded(object sender, EventArgs e)
{
  var targetInput = sender as FrameworkElement;
  targetInput.Loaded -= OnTargetInputLoaded;

  Point targetPositionRelativeToWrapPanel = 
    targetInput.TransformToVisual(this.nList).Transform(new Point(0, 0));

  Point targetPositionRelativeToMainWindow = 
    targetInput.TransformToVisual(this).Transform(new Point(0, 0));
}
  • Related