2015-07-06 3 views
0

Я пытаюсь получить пункт для экспорта в PDF
Когда я держусь деталь, она показывает мне menuFlyout Экспорт в PDF
поэтому я стараюсь, чтобы получить индекс, чтобы быть способный экспортировать его.
XamlПолучить выбранный элемент ListBox WP8.1 C#

<Page 
x:Class="WritePad_CSharpSample.ReadWritePadNoteList" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:local="using:WritePad_CSharpSample" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
mc:Ignorable="d" 
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> 

<Grid> 
    <StackPanel Grid.Row="0" Margin="12,17,0,28"> 
     <TextBlock Text="Read All Notes with listbox" Margin="9,-7,0,0" FontSize="28"/> 
    </StackPanel> 

    <ListBox Background="Transparent" Margin="6" Height="auto" BorderThickness="2" MaxHeight="580" Grid.Row="1" x:Name="listBoxobj" SelectionChanged="listBoxobj_SelectionChanged"> 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <Grid Width="350" > 
        <Border Margin="5" BorderBrush="White" BorderThickness="1"> 
         <Grid Holding="Grid_Holding" VerticalAlignment="Stretch"> 
          <Grid.RowDefinitions> 
           <RowDefinition Height="Auto"/> 
           <RowDefinition Height="Auto"/> 
          </Grid.RowDefinitions> 

          <FlyoutBase.AttachedFlyout> 
           <MenuFlyout> 
            <MenuFlyoutItem x:Name="EditButton" 
              Text="Export To PDF" 
              Click="EditButton_Click" 
                /> 
           </MenuFlyout> 
          </FlyoutBase.AttachedFlyout> 
          <TextBlock Margin="5,0,0,0" Grid.Row="0" x:Name="NameTxt" TextWrapping="Wrap" Text="{Binding Name}" FontSize="28" Foreground="White"/> 
          <TextBlock HorizontalAlignment="Right" Margin="0,0,35,0" Grid.Row="3" x:Name="CreateddateTxt" Foreground="White" FontSize="18" TextWrapping="Wrap" Text="{Binding CreationDate}" /> 
         </Grid> 
        </Border> 
       </Grid> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 

</Grid> 

<Page.BottomAppBar> 
    <CommandBar> 
     <CommandBar.PrimaryCommands> 
      <AppBarButton Label="New" Click="AddNewNoteClick" /> 
      <AppBarButton x:Name="deleteAppBarButton" Label="Delete All" Click="DeleteAllNoteClick" /> 
     </CommandBar.PrimaryCommands> 
    </CommandBar> 
</Page.BottomAppBar> 

C#

using System; 
using System.Collections.Generic; 
using System.Collections.ObjectModel; 
using System.IO; 
using System.Linq; 
using System.Runtime.InteropServices.WindowsRuntime; 
using System.Text; 
using Windows.Foundation; 
using Windows.Foundation.Collections; 
using Windows.Storage; 
using Windows.System; 
using Windows.UI.Popups; 
using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls; 
using Windows.UI.Xaml.Controls.Primitives; 
using Windows.UI.Xaml.Data; 
using Windows.UI.Xaml.Input; 
using Windows.UI.Xaml.Media; 
using Windows.UI.Xaml.Navigation; 
using WritePad_CSharpSample.Helpers; 
using WritePad_CSharpSample.Model; 

namespace WritePad_CSharpSample 
{ 

    public sealed partial class ReadWritePadNoteList : Page 
    { 
     ObservableCollection<WritePadFileContent> DB_ContactList = new ObservableCollection<WritePadFileContent>(); 

     int Selected_ContactId = 0; 
     DatabaseHelperClass Db_Helper = new DatabaseHelperClass(); 
     WritePadFileContent currentcontact = new WritePadFileContent(); 
     string name = ""; 
     string desc = ""; 
     public ReadWritePadNoteList() 
     { 
      this.InitializeComponent(); 
      this.Loaded += ReadWritePadFileContentList_Loaded; 
     } 

     private void ReadWritePadFileContentList_Loaded(object sender, RoutedEventArgs e) 
     { 
      ReadAllWritePadFileContent dbnote = new ReadAllWritePadFileContent(); 
      DB_ContactList = dbnote.GetAllContacts();//Get all DB contacts 
      if (DB_ContactList.Count > 0) 
       deleteAppBarButton.IsEnabled = true; 
      else 
       deleteAppBarButton.IsEnabled = false; 
      listBoxobj.ItemsSource = DB_ContactList.OrderByDescending(i => i.Id).ToList();//Binding DB data to LISTBOX and Latest contact ID can Display first. 

     } 




    protected override void OnNavigatedTo(NavigationEventArgs e) 
      { } 
private void AddNewNoteClick(object sender, RoutedEventArgs e) 
     { 


    Frame.Navigate(typeof(MainPage)); 
    } 

private void listBoxobj_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    int SelectedContactID = 0; 
    if (listBoxobj.SelectedIndex != -1) 
    { 
     WritePadFileContent listitem = listBoxobj.SelectedItem as WritePadFileContent;//Get slected listbox item contact ID 
     Frame.Navigate(typeof(DeleteUpdateNote), SelectedContactID = listitem.Id); 

    } 
} 

private async void DeleteAllNoteClick(object sender, RoutedEventArgs e) 
{ 
     var dialog = new MessageDialog("Are you sure you want to remove all your data ?"); 
     dialog.Commands.Add(new UICommand("No", new UICommandInvokedHandler(Command))); 
     dialog.Commands.Add(new UICommand("Yes", new UICommandInvokedHandler(Command))); 
     await dialog.ShowAsync(); 
    } 

    private void Command(IUICommand command) 
    { 
     if (command.Label.Equals("Yes")) 
     { 
      DatabaseHelperClass Db_Helper = new DatabaseHelperClass(); 
      Db_Helper.DeleteAllWritePadFileContent();//delete all DB contacts 
      DB_ContactList.Clear();//Clear collections 
      //Btn_Delete.IsEnabled = false; 
      deleteAppBarButton.IsEnabled = false; 
      listBoxobj.ItemsSource = DB_ContactList; 
     } 
    } 





    private void Grid_Holding(object sender, HoldingRoutedEventArgs e) 
     { 
      FrameworkElement senderElement = sender as FrameworkElement; 
      FlyoutBase flyoutBase = FlyoutBase.GetAttachedFlyout(senderElement); 

      flyoutBase.ShowAt(senderElement); 
     } 

     private async void EditButton_Click(object sender, RoutedEventArgs e) 
     { 

      WritePadFileContent listitem = (sender as ListBox).DataContext as WritePadFileContent; 
      MessageDialog messageDialog = new MessageDialog(listitem.Name.ToString()); 
      await messageDialog.ShowAsync(); 
      //pdf code work 
     } 
    } 
} 

за исключением здесь, это возвращать нуль, так что любая помощь, чтобы получить деталь, когда я держусь от ListBox?

ответ

1

Когда вы нажимаете и удерживаете, ListViewItem не выбирается, поэтому SelectedItem всегда будет null. Вместо этого, вы должны получить значение DataContext от MenuFlyoutItem, как это:

private async void EditButton_Click(object sender, RoutedEventArgs e) 
    { 
     WritePadFileContent listitem = (e.OriginalSource as MenuFlyoutItem).DataContext as WritePadFileContent; 
     MessageDialog messageDialog = new MessageDialog(listitem.Name.ToString()); 
     await messageDialog.ShowAsync(); 



     //code for export to pdf, it works 
    } 
+0

имя списка является listBoxobj – Amin

+0

как вы добавляете детали к нему? – thewindev

+0

У меня есть этот метод для добавления элемента private void listBoxobj_SelectionChanged (object sender, SelectionChangedEventArgs e) { int SelectedContactID = 0; если (listBoxobj.SelectedIndex = -1!) { WritePadFileContent ListItem = listBoxobj.SelectedItem в WritePadFileContent; // Получаем slected ListBox элемент контакт ID Frame.Navigate (TypeOf (DeleteUpdateNote), SelectedContactID = listitem.Id); }} и даже если я пытаюсь ур метод, никогда не войти в эту часть – Amin

Смежные вопросы