嗨,这是我正在使用xaml页面,我想用所选项目导航。
<ListBox x:Name="NotchsList11" Margin="0,0,0,0" Grid.Row="3" HorizontalAlignment="left" Width="Auto" Grid.RowSpan="2">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel VerticalAlignment="Top" Width="Auto">
<ListBox ItemsSource="{Binding Images}" Width="Auto" ScrollViewer.VerticalScrollBarVisibility="Disabled" SelectionChanged="NotchsList11_SelectionChanged">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Top">
</StackPanel>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Image Source="{Binding}" Width="152" Height="90" Stretch="Fill" VerticalAlignment="Top">
</Image>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我的xaml.cs页面代码如下所示
private void NotchsList11_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Notch selectedItemData = (sender as ListBox).SelectedItem as Notch;
if(selectedItemData != null)
{
NavigationService.Navigate(new Uri(string.Format("/Test.xaml?parameter={0}",selectedItemData.articleid), UriKind.Relative));
}
}
如果我选择任何一个项目我无法导航到其他页面,因为我收到错误selectedItemData是null.so任何人都可以帮助我吗?
答案 0 :(得分:0)
请勿尝试从发件人对象中提取。如果实际上代码认为某个项目是真正选中的而不是null,则只需从列表对象中直接提取所需内容。
您只需将SelectionChanged方法更改为如下所示:
private void NotchsList11_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (NotchsList11.SelectedItem != null)
{
NavigationService.Navigate(new Uri(string.Format("/Test.xaml?parameter={0}",
(NotchsList11.SelectedItem as Notch).articleid), UriKind.Relative));
}
}
答案 1 :(得分:0)
一个。
private void NotchsList11_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Notch selectedItemData = NotchsList11.SelectedItem as Notch;
if (selectedItemData != null)
{
NavigationService.Navigate(new Uri(string.Format("/Test.xaml?parameter={0}",selectedItemData.articleid), UriKind.Relative));
}
}
B中。或者您可以将整个SelectedItemData对象用作数据上下文
private void NotchsList11_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Notch selectedItemData = NotchsList11.SelectedItem as Notch;
if (selectedItemData != null)
{
NavigationService.Navigate(new Uri("/Test.xaml", UriKind.Relative));
FrameworkElement root = Application.Current.RootVisual as FrameworkElement;
root.DataContext = selectedItemData;
}
}
备注:在Test页面中,您可以使用(Notch)DataContext引用Class的实例,这样您就可以将Image数据用作((Notch)DataContext).Image
℃。或者,这样:
private void NotchsList11_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count > 0)
{
NavigationService.Navigate(new Uri(((Notch)e.AddedItems[0]).articleid, UriKind.Relative));
((ListBox)sender).SelectedIndex = -1;
备注:Notch是您将ItemSource绑定到ListBox
的类祝你好运 司帕索