【问题标题】:Get item from Longlistselector Hold event从 Longlistselector Hold 事件中获取项目
【发布时间】:2014-03-07 05:49:32
【问题描述】:

我正在使用longlistselector,我想在Hold 事件中获取所选项目中的文本。不幸的是,Hold 没有创建SelectedItem,所以我必须做一个解决方法。我已经阅读了很多有关此问题的信息,但无法获得完全有效的解决方案。这是我得到的错误:Unable to cast object of typePhoneApp2.Favs to type 'System.String'.`。仅当我按住项目中文本旁边的空白区域时,才会出现此错误。我该如何解决这个问题?

相关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>

【问题讨论】:

    标签: c# windows-phone-8 longlistselector


    【解决方案1】:

    在您的情况下,element.DataContext 可能是您的自定义类 Favs

    所以你应该做以下转换:

    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;
            }       
    
            ....
    

    【讨论】:

    • +1,但是当用户在列表之外持有时也会导致问题 - 然后将使用 Grid 作为 FrameworkElement 和 DataContext = null 触发事件;
    【解决方案2】:

    那是因为你捕获了许多不同的FrameworkElements(TextBlock、Border 等)并且只有TextBlock 可以转换为string

    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 时有效。如果用户在 Text 后面保留一个空格,则它是一个 Border,DataContext 是 Favs - 您可以执行适当的转换并取出您的变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-22
      • 2018-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多