如何在文本块中显示列表框所选项目

时间:2017-07-31 07:15:55

标签: c# xaml listbox windows-phone-8.1

我有一个列表框,其中使用绑定填充数据,我想将选定列表项中的名称和年龄显示在下一页中的文本块中。

XAML

<ListBox x:Name="listBoxobj" Background="Transparent" Height="388" Margin="22,0,0,0" SelectionChanged="listBoxobj_SelectionChanged">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <!--<Border BorderBrush="DarkGreen" BorderThickness="4">-->
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="auto"/>
                            <RowDefinition Height="auto"/>
                        </Grid.RowDefinitions>
                        <TextBlock  x:Name="txtName1" 
                                    Text="{Binding Name}" 
                                    Grid.Row="0" 
                                    Width="400" 
                                    Height="40"  
                                    Foreground="White" 
                                    FontSize="20" 
                                    Margin="8,0,-48,0"/>
                        <TextBlock x:Name="Age1" 
                                   Text="{Binding Age}" 
                                   Grid.Row="1" 
                                   Width="400" 
                                   Height="40"  
                                   Foreground="White" 
                                   FontSize="18" 
                                   Margin="8,0,-48,0"/>
                    </Grid>
                <!--</Border>-->
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

我试着这样做,

private void listBoxobj_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {         
        object  person = listBoxobj.SelectedItem;           
        Frame.Navigate(typeof(Page2), person);        
    }

但我不明白如何从NavigationEventArgs e中获取值以在一个textBlock中显示Name,在另一个textBlock中显示Age。 数据通过此绑定...

 ObservableCollection<MyData> Details = new ObservableCollection<MyData>();
        Details.Add(new MyData() { LineOne = "Teena", LineTwo = "20" });
        Details.Add(new MyData() { LineOne = "Riya", LineTwo = "21" });
        Details.Add(new MyData() { LineOne = "Priya", LineTwo = "22" });
        Details.Add(new MyData() { LineOne = "kila", LineTwo = "23" });
        this.listBoxobj.ItemsSource = Details;

1 个答案:

答案 0 :(得分:0)

我找到了答案,

private void listBoxobj_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        MyData list_item = listBoxobj.SelectedItem as  MyData;    
        Frame.Navigate(typeof(Page2), list_item);        
    }

并在下一页中,以这种方式派生参数

 protected override void OnNavigatedTo(NavigationEventArgs e)
    {
       textBlock1.Text = ((Appbar_Sample.MyData)e.Parameter).LineOne;
        textBlock2.Text = ((Appbar_Sample.MyData)e.Parameter).LineTwo;
    }