我将一些项目绑定到listbox。每当点击特定的listitem时,我想在另一个页面中显示这些子项目。
请告诉我如何实现这一点。
每当点击特定列表项时如何获取listitem id?
答案 0 :(得分:28)
为了澄清(如果您不想创建新的DataBound应用程序而只想要答案),您应该查看 selectionchanged事件,而不是依赖于列表框项目的click事件。列表框本身。
例如:
<ListBox SelectionChanged="MainListBox_SelectionChanged">
// Handle selection changed on ListBox
private void MainListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// If selected index is -1 (no selection) do nothing
if (MainListBox.SelectedIndex == -1)
return;
// Navigate to the new page
NavigationService.Navigate(new Uri("/DetailsPage.xaml?selectedItem=" + MainListBox.SelectedIndex, UriKind.Relative));
// Reset selected index to -1 (no selection)
MainListBox.SelectedIndex = -1;
}
答案 1 :(得分:3)
查看作为新DataBound应用程序的一部分创建的代码。它就是这样做的。
答案 2 :(得分:1)
MVVM解决方案
使用以下库:
xmlns:GalaSoft_MvvmLight_Command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP71"
xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit" <-- (optional, only for the ContextMenu)
XAML示例:
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox x:Name="categoryListBox" Margin="0,0,-12,0" ItemsSource="{Binding CategoryItems}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel x:Name="stackPanel" Margin="0,0,0,17" Width="432" Height="78">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Tap">
<GalaSoft_MvvmLight_Command:EventToCommand
Command="{Binding Main.OpenCategoryCommand, Source={StaticResource Locator}, Mode=OneWay}"
CommandParameter="{Binding Mode=OneWay}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu>
<toolkit:MenuItem Header="Remove" />
<toolkit:MenuItem Header="Show" />
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
<TextBlock Text="{Binding Name}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
<TextBlock Text="{Binding Note}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
答案 3 :(得分:1)
对于将MVVM样式绑定到列表中项目的简单命令,您还可以将整个项目模板包含在一个按钮中,并将按钮的Command属性挂钩,如下所示:
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Button Command="{Binding Path=SomeCommandOnItemViewModel, Mode=OneWay}">
<Button.Template>
<ControlTemplate>
<!-- Your listitem styling goes here -->
</ControlTemplate>
</Button.Template>
</Button>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>