Siyh
Siyh

Reputation: 1809

How do I get the pixel locations of text and other elements in a UWP ListView?

I have a ListView in my UWP app with an ItemTemplate that consists of a Path geometry and a TextBox:

<ListView 
    x:Name="ListView"
    CanDragItems="True"
    CanReorderItems="True"
    ItemsSource="{x:Bind Categories}">

    <ListView.ItemTemplate>
        <DataTemplate x:DataType="myData:Category">
            <StackPanel
                Orientation="Horizontal"
                ToolTipService.ToolTip="{x:Bind CategoryString, Mode=OneWay}">

                <Path                                        
                    Margin="14, 10, 4, 0"
                    Width="10"
                    Height="10"
                    VerticalAlignment="Center"
                    HorizontalAlignment="Center"
                    Data="{x:Bind SymbolGeometry, Mode=OneWay}"
                    Fill="{x:Bind Colour, Mode=OneWay}"/>

                <TextBox 
                    BorderThickness="0"
                    Background="Transparent"
                    Text="{x:Bind LegendLabel, Mode=TwoWay}"/>

            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

As part of exporting a piece of the UI to an SVG I would like to find the locations (in pixel coordinates relative to any parent item) of the TextBox text and Path geometry for each item in the ListView. Does anybody know how to achieve this? As the ListView items are dependant on user input I'm unsure how to retrieve the necessary information.

I'm aware UIElements can be converted to bitmaps for export, however this does not fulfil the requirements of the app.

Upvotes: 0

Views: 35

Answers (1)

YanGu
YanGu

Reputation: 3032

You could use the UIElement.TransformToVisual(UIElement) Method and GeneralTransform.TransformPoint(Point) Method to get the locations of UIElement objects.

Please check the following code:

for(int i=0;i<ListView.Items.Count;i++)
{
    var item = ListView.ContainerFromIndex(i) as ListViewItem;

    var path = VisualTreeHelper.GetChild(item.ContentTemplateRoot as DependencyObject, 0) as Windows.UI.Xaml.Shapes.Path;
    var box = VisualTreeHelper.GetChild(item.ContentTemplateRoot as DependencyObject, 1) as TextBox;
    var visual1 = path.TransformToVisual(ListView); //Select the ListView control as the parent element.
    var point = visual1.TransformPoint(new Point(0, 0));

    var visual2 = box.TransformToVisual(ListView);
    var point2 = visual2.TransformPoint(new Point(0, 0));

}

Upvotes: 1

Related Questions