2014-03-06 5 views
0

나는 longlistselector을 사용하고 있으며, Hold 이벤트에서 선택한 항목에있는 텍스트를 받고 싶습니다. 불행히도 HoldSelectedItem을 만들지 않으므로 해결 방법을 찾아야합니다. 나는이 문제에 관해 꽤 많이 읽었지만 완전히 작동하는 해결책을 얻을 수는 없다. 이것은 내가 얻는 오류입니다 : PhoneApp2.Favs 'System.String'.`을 입력합니다. 이 오류는 항목의 텍스트 옆에 열린 공간을 누르고있을 때만 나타납니다. 이 문제를 어떻게 해결할 수 있습니까?Longlistselector에서 제품 가져 오기

관련 C 번호 :

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Navigation; 
using Microsoft.Phone.Controls; 
using Microsoft.Phone.Shell; 
using System.Windows.Media; 
using System.Collections.ObjectModel; 
using System.Xml; 
using PhoneApp2.Resources; 
using System.Xml.Linq; 
using System.IO; 
using System.IO.IsolatedStorage; 
using System.Windows.Resources; 

namespace PhoneApp2 
{ 
    public class Favs 
    { 
     private string drank; 

     public string Name 
     { 
      get { return drank; } 
      set { drank = value; } 
     } 
     public Favs(string addition) 
     { 
      this.Name = addition; 
     } 
    } 

    public partial class Favorites : PhoneApplicationPage 
    { 
     ObservableCollection<Favs> Favlist = new ObservableCollection<Favs>(); 
     Array list; 
     Boolean alpha = false; 
     public Favorites() 
     { 
      InitializeComponent(); 
     } 

     protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) 
     { 
      //Populate LLL listBar 
      listFavs.ItemsSource = Favlist; 

      try 
      { 
       // copy the xml file to isolated storage 
       using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication()) 
       { 
        if (!file.FileExists("favorites.xml")) 
        { 
         StreamResourceInfo sr_en = Application.GetResourceStream(new Uri("Resources\\favorites.xml", UriKind.Relative)); 
         using (BinaryReader br_en = new BinaryReader(sr_en.Stream)) 
         { 
          byte[] data = br_en.ReadBytes((int)sr_en.Stream.Length); 
          //Write the file. 
          using (BinaryWriter bw = new BinaryWriter(file.CreateFile("favorites.xml"))) 
          { 
           bw.Write(data); 
           bw.Close(); 
          } 
         } 
        } 
        // work with file at isolatedstorage 
        using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("favorites.xml", FileMode.Open, file)) 
        { 
         XDocument xDoc = XDocument.Load(stream, LoadOptions.None); 
         list = xDoc.Descendants("cocktail").Select(n => n.Value).ToArray(); 
         Array.Sort(list); 
         alpha = true; 
         foreach (string name in list) 
         { 
          Favlist.Add(new Favs(name)); 
         } 

        } 
       } 
       Dispatcher.BeginInvoke(() => 
       { 
        pbLoading.IsIndeterminate = false; 
        pbLoading.Visibility = Visibility.Collapsed; 
       }); 
      } 
      catch (IOException IOExc) 
      { 
       MessageBox.Show(IOExc.Message); 
      } 
      catch (XmlException XmlExc) 
      { 
       MessageBox.Show(XmlExc.Message); 
      } 
      catch (Exception myExc) 
      { 
       MessageBox.Show(myExc.Message); 
      } 
     } 

     private void listFavs_Hold(object sender, System.Windows.Input.GestureEventArgs e) 
     { 
      try 
      { 
       FrameworkElement element = (FrameworkElement)e.OriginalSource; 
       String item = (String)element.DataContext; 
       var booze = item.ToString(); 

       Dispatcher.BeginInvoke(() => 
       { 
        CustomMessageBox messageBox = new CustomMessageBox() 
        { 
         Caption = "Delete " + booze, 
         Message = "Are you sure you want to remove " + booze + " from your favorites? This cannot be made undone!", 
         LeftButtonContent = "Yes", 
         RightButtonContent = "No" 
        }; 
        messageBox.Dismissed += (s1, e1) => 
        { 
         switch (e1.Result) 
         { 
          case CustomMessageBoxResult.LeftButton: 
           using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication()) 
           { 
            using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("favorites.xml", FileMode.Open, file)) 
            { 
             XDocument xDoc = XDocument.Load(stream, LoadOptions.None); 
             // delete node 
             xDoc.Descendants("data").Elements("cocktail").Where(x => x.Value == booze).DescendantsAndSelf().Remove(); 
             xDoc.Save(stream); 

             Favlist.Clear(); 

             list = xDoc.Descendants("cocktail").Select(n => n.Value).ToArray(); 
             Array.Sort(list); 
             alpha = true; 
             foreach (string name in list) 
             { 
              Favlist.Add(new Favs(name)); 
             } 
            } 
           } 
           break; 
          case CustomMessageBoxResult.RightButton: 
           //do nothing 
           break; 
          case CustomMessageBoxResult.None: 
           //do nothing 
           break; 
          default: 
           break; 
         } 
        }; 

        messageBox.Show(); 
       }); 
      } 
      catch (InvalidCastException ICExc) 
      { 
       MessageBox.Show(ICExc.Message); 
      } 
      catch (IOException IOExc) 
      { 
       MessageBox.Show(IOExc.Message); 
      } 
      catch (XmlException XmlExc) 
      { 
       MessageBox.Show(XmlExc.Message); 
      } 
      catch (NullReferenceException NRExc) 
      { 
       MessageBox.Show(NRExc.Message); 
      } 
      catch (Exception myExc) 
      { 
       MessageBox.Show(myExc.Message); 
      } 
     } 
    } 
} 

XAML :

아마
<phone:PhoneApplicationPage 
    x:Class="PhoneApp2.Favorites" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" 
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    FontFamily="{StaticResource PhoneFontFamilyNormal}" 
    FontSize="{StaticResource PhoneFontSizeNormal}" 
    Foreground="{StaticResource PhoneForegroundBrush}" 
    SupportedOrientations="Portrait" Orientation="Portrait" 
    mc:Ignorable="d" 
    shell:SystemTray.IsVisible="True"> 

    <!--LayoutRoot is the root grid where all page content is placed--> 
    <Grid x:Name="LayoutRoot"> 
     <Grid.Background> 
      <ImageBrush Stretch="Fill" ImageSource="/Assets/AlignmentGrid.png"/> 
     </Grid.Background> 
     <Grid.RowDefinitions> 
      <RowDefinition Height="Auto"/> 
      <RowDefinition Height="*"/> 
     </Grid.RowDefinitions> 

     <Grid x:Name="Header" Grid.Row="0" Margin="12,17,0,616" Grid.RowSpan="2"> 
      <TextBlock Text="Cocktail" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0,242,46"/> 
      <TextBlock Text="Favorites" Style="{StaticResource PhoneTextTitle1Style}" Margin="10,50,101,0" FontWeight="Bold"/> 
      <Button x:Name="btnSettings" Content="" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="367,60,0,-50" Height="86" Width="91" Click="btnSettings_Click" BorderThickness="0"> 
       <Button.Foreground> 
        <ImageBrush Stretch="Fill"/> 
       </Button.Foreground> 
       <!--<Button.Background> 
        <ImageBrush Stretch="Fill" ImageSource="feature.settings.png"/> 
       </Button.Background>--> 
      </Button> 
     </Grid> 

     <!--ContentPanel - place additional content here--> 
     <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,157,12,0"> 
      <phone:LongListSelector x:Name="listFavs" HorizontalAlignment="Left" Height="601" VerticalAlignment="Top" Width="456" Tap="listFavs_Tap" Hold="listFavs_Hold"> 
       <phone:LongListSelector.ItemTemplate> 
        <DataTemplate> 
         <Button Content="{Binding Name}" FontSize="36" HorizontalContentAlignment="left" HorizontalAlignment="Left" Height="82" Margin="0,-11,0,0" VerticalAlignment="Top" Width="456" Padding="0,0,0,0" BorderThickness="0"> 
         </Button> 
        </DataTemplate> 
       </phone:LongListSelector.ItemTemplate> 
      </phone:LongListSelector> 
      <ProgressBar x:Name="pbLoading" HorizontalAlignment="Left" Height="20" Margin="127,271,0,0" VerticalAlignment="Top" Width="200" IsIndeterminate="True"/> 
     </Grid> 
    </Grid> 

</phone:PhoneApplicationPage> 

답변

3

element.DataContext 귀하의 경우는 사용자 정의 클래스 Favs입니다.

그래서 당신은 주조 다음을 수행해야합니다 : 당신이 많은 다른 FrameworkElements (등등 TextBlock의 국경과)을 사로 잡고있다 만 TextBlockstring에 캐스트 할 수 있기 때문이다

private void listFavs_Hold(object sender, System.Windows.Input.GestureEventArgs e) 
{ 
    try 
    { 
     FrameworkElement element = (FrameworkElement)e.OriginalSource; 
     string item = null; 

     if(element.DataContext is Favs) 
     { 
      Favs itemTmp = (Favs)element.DataContext; 
      item = itemTmp.Name; 
     } 
     else 
     { 
      item = (string)element.DataContext; 
     }  

     .... 
+0

+1하지만 사용자가 목록 외부에있을 때도 문제가 발생합니다. 그런 다음 GridElement 및 DataContext = null로 Grid에서 이벤트가 발생합니다. – Romasz

0

:

private void listFavs_Hold(object sender, System.Windows.Input.GestureEventArgs e) 
{ 
    try 
    { 
     FrameworkElement element = (FrameworkElement)e.OriginalSource; 
     if (element is TextBlock) 
     { 
      String item = (String)element.DataContext; 
      var booze = item.ToString(); 
      // rest of code 
     } 
    } 

이 코드는 사용자가 텍스트를 누른 경우에만 작동합니다. Text 다음에 빈 공간이 있으면 DataContext가 FavsBorder입니다. 적절한 캐스팅을 수행하고 변수를 추출 할 수 있습니다.

관련 문제