locked
Windows Phone 8.1 - Way to check what listview item was clicked.

    Question

  • Hi. Want to know how to check what listview item was clicked. I want to navigate to different pages depending on which listviewitem was clicked.

    My XAML is like this:

    <Page
        x:Class="wp8.Pages.RegistrationFinalStagePage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:wp8.Pages"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Loaded="Page_Loaded">
    
        <Grid Margin="15,0,15,0">
            <Grid.RowDefinitions>
                <RowDefinition Height="80"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
    
            <ListView x:Name="ListView1" Grid.Row="1" IsItemClickEnabled="True" ItemClick="ListView_ItemClick">
                <ListView.ItemContainerStyle>
                    <Style TargetType="ListViewItem">
                        <Setter Property="HorizontalContentAlignment" Value="Stretch" />
                    </Style>
                </ListView.ItemContainerStyle>
                <ListViewItem x:Name="ListViewItem1">
                        <TextBlock Text="Page 1"/>
                </ListViewItem>
                <ListViewItem x:Name="ListViewItem2">
                        <TextBlock Text="Page 2"/>
                </ListViewItem>
                <ListViewItem x:Name="ListViewItem3">
                        <TextBlock Text="Page 3"/>
                </ListViewItem>
                <ListViewItem x:Name="ListViewItem4">
                        <TextBlock Text="Page 4"/>
                </ListViewItem>
            </ListView>
        </Grid>
    
    </Page>


    • Edited by Vil Grim Tuesday, August 05, 2014 8:35 AM
    Tuesday, August 05, 2014 8:31 AM

Answers

  • The easiest solution would probably be to cast the ItemClickEventArgs.ClickedItem property to a TextBlock in the ItemClick event handler and then check the value of its Text property:

            private void ListView_ItemClick(object sender, ItemClickEventArgs e)
            {
                TextBlock txtBlock = e.ClickedItem as TextBlock;
                if (txtBlock != null && txtBlock.Text == "Page 2")
                {
                    //do something...
                }
            }


    • Edited by Magnus (MM8)MVP Tuesday, August 05, 2014 8:54 AM
    • Marked as answer by Vil Grim Wednesday, August 06, 2014 6:20 AM
    Tuesday, August 05, 2014 8:53 AM