ChaosSpeeder
ChaosSpeeder

Reputation: 3508

How can I obtain the coordinates of a selected item container in a WPF ListView

I want to display some WPF elements near to the selected item of a ListView. How can I obtain the coordinates (screen or relative) of the selected ListViewItem?

<ListView 
    x:Name="TechSchoolListView"
    ClipToBounds="False"
    Width="Auto" Height="Auto" 
    HorizontalContentAlignment="Stretch" 
    VerticalContentAlignment="Top" 
    ItemTemplate="{DynamicResource TechSchoolDataTemplate}" 
    ItemsSource="{Binding Path=TechSchoolResearchList, Mode=Default}" 
    SelectedIndex="1"
    SelectedValue="{Binding Path=SelectedTechSchool, Mode=Default}" 
    SelectionChanged="TechSchoolList_SelectionChanged" 
    ItemContainerStyle="{DynamicResource TechSchoolItemContainerStyle}" 
    ScrollViewer.CanContentScroll="False" 
    ScrollViewer.VerticalScrollBarVisibility="Disabled" >
    <ListView.Background>
        <SolidColorBrush Color="{DynamicResource PanelBackgroundColor}"/>
    </ListView.Background>
</ListView>

Upvotes: 3

Views: 5997

Answers (3)

PWCoder
PWCoder

Reputation: 113

Although Franci Penov's answer is correct I would like to give a code sample to show how what he was saying worked for me.

UIElement selectedContainer = (UIElement)(sender as 
ListView).ItemContainerGenerator.ContainerFromIndex((sender as 
ListView).SelectedIndex);
Point startPoint = selectedContainer.PointToScreen(new Point(0,0));

Upvotes: 2

ChaosSpeeder
ChaosSpeeder

Reputation: 3508

Now I have found a solution by myself. I have searched for a simple property, but it made no sense, because all UI Elements in the WPF are relative.

This code seems to be working:

        UIElement selectedContainer = (UIElement) TechSchoolListView.ItemContainerGenerator.ContainerFromIndex(TechSchoolListView.SelectedIndex);
        Point cursorPos = selectedContainer.TranslatePoint(new Point(selectedContainer.DesiredSize.Width, 0.0), Page);
        PanelCursor.Height = selectedContainer.DesiredSize.Height;
        PanelCursor.Margin = new Thickness(400, cursorPos.Y, 0.0, 0.0);

Upvotes: 4

Franci Penov
Franci Penov

Reputation: 75981

You should use ContainerFromElement to get the item's container, which is a visual and from there you can get the coordinates. You can't express this in XAML, however. You need to do it in code, on one of the ListView events, raised when the selected item is changed. Btw, keep in mind that the item can be its own container.

You can't do this in XAML, as there's no attached property on the item that shows the item is selected. (though I haven't played with WPF in a while, so that might have changed)

Upvotes: 3

Related Questions