如何从Windows Phone的列表框中选择一个项目?

时间:2013-10-25 13:32:26

标签: c# windows-phone-7

我有一份数据清单, 每一行都会显示一个数据,并且会有一个按钮,当我点击显示的数据时,我想给上一页提供一些数据,当我点击同一行中的按钮时,我想将相同的数据发送到下一页。

我的Xaml代码,

<ListBox x:Name="List" HorizontalAlignment="Left" Height="612" Margin="6,7,0,0" VerticalAlignment="Top" Width="443" SelectionChanged="List_SelectionChanged_1">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" Width="420" Height="50">
                        <TextBlock x:Name="tbName" Width="400" Height="44" FontSize="22" FontWeight="Bold" Text="{Binding Name}" />
                        <Button x:Name="DetailButton" Height="44" Width="20" Content=">" FontWeight="Bold" Click="DetailButton_Click_1"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

List_SelectionChanged_1 事件处理程序的代码是,

private void List_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
    {
        Display selectedItemData = (sender as ListBox).SelectedValue as Display;            
        NavigationService.Navigate("/Page1.xaml",selectedItemData);
    }

我的 DetailButton_Click_1 事件处理程序是

private void DetailButton_Click_1(object sender, RoutedEventArgs e)
    {
        Display selectedItemData = (sender as ListBox).SelectedValue as Display;
        NavigationService.Navigate("/page3.xaml", selectedItemData);
    }

* List_SelectionChanged_1 *的工作正常,但我在执行时遇到异常

Display selectedItemData = (sender as ListBox).SelectedValue as Display;
DetailButton_Click_1

,我得到一个空异常的例外,

An exception of type 'System.NullReferenceException' occurred in ExpenseApp.DLL but was not handled in user code

我应该怎么做让它起作用?

2 个答案:

答案 0 :(得分:1)

根本问题是按钮点击事件的发件人是按钮,而不是ListBox。

另请注意,单击数据模板上的按钮不一定会在列表中选择该项目。尝试抓取单击的项目的数据上下文,并使用它而不是.SelectedItem

private void DetailButton_Click_1(object sender, RoutedEventArgs e)
{
    var clickedUIElement =  sender as Button;
    if (null == clickedUIElement) { Return; }
    Display selectedItemData = clickedUIElement.DataContext as Display;
    if(null != selectedItemData)
    {
        NavigationService.Navigate("/page3.xaml", selectedItemData);
    }
}

您的代码原样会有一个空引用,因为您无法将Button转换为ListBox。

答案 1 :(得分:0)

在执行代码之前尝试验证selectvalue是否为null:

 private void DetailButton_Click_1(object sender, RoutedEventArgs e)
    {
        If ((sender as ListBox).SelectedValue != null){
             Display selectedItemData = (sender as ListBox).SelectedValue as Display;
             NavigationService.Navigate("/page3.xaml", selectedItemData);
        }
    }