2013-10-25 160 views
-1

我有一個數據列表, 每行都會顯示一個數據,並且會有一個按鈕,當我點擊顯示的數據時,我想給一些數據到前一頁,當我點擊同一行中的按鈕時,我想要將相同的數據發送到下一頁。如何從Windows Phone的列表框中選擇一個項目?

我的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 *,但我得到一個異常在執行DetailButton_Click_1

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

,我得到一個異常的空異常,

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

我應該怎麼做使它工作?

回答

1

根本的問題是,按鈕點擊事件的發送者是按鈕,而不是列表框。

另請注意,單擊數據模板上的按鈕不一定會在列表中選擇該項目。試圖抓住被點擊項目的數據上下文,並用它來代替.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); 
    } 
} 

您的代碼,因爲它的立場,將有一個空引用,因爲你可以不投一個按鈕,一個列表框。

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); 
     } 
    } 
相關問題