简体   繁体   English

将绑定的列表框数据传递到数据透视页? Windows Phone 7

[英]Passing binded listbox data to pivot page? Windows Phone 7

I am having an absolute headache figuring this out. 我对此非常头痛。 I badly need some help with this. 我非常需要帮助。

I have a listbox populated with items called with a public static void RSS feed class. 我有一个listbox填充有使用公共静态void RSS feed类调用的项目。 Once the listbox populates with the databound items, I click on an item and it passes it through to my pivot page. 一旦列表框填充了数据绑定的项目,我单击一个项目,它将其传递到我的数据透视页。 However, when I flick left or right, all I get is the same image. 但是,当我左右滑动时,我得到的只是同一张图像。 That is my problem, and what I would like to have happen is if the user flicks left, it loads the previous RSS image. 那是我的问题,我想发生的事情是,如果用户向左滑动,它将加载先前的RSS图像。 I would like it to also go to the next picture if the If the user scrolls right. 如果用户向右滚动,我希望它也转到下一张图片。

The community has been helpful in providing links to some things, or saying to not use the listbox, etc. However while I am new to all of this, I would just like concrete help with the code i have to achieve what I have in mind. 社区在提供指向某些内容的链接或说不使用列表框等方面有所帮助。但是,尽管我对此不陌生,但我想在代码方面提供具体帮助,以实现我的初衷。 It's nothing personal -- I just need to take babysteps with this before I get worked up with other things I have no clue about. 没什么私人的-我只需要采取一些步骤,然后再处理其他我不知道的事情。

Here is all my relevant code. 这是我所有相关的代码。

Page 1 Xaml: 第1页Xaml:

    <ListBox x:Name="listbox" HorizontalContentAlignment="Stretch" ItemsSource="{Binding items}" SelectionChanged="listbox_SelectionChanged">
            <ListBox.ItemTemplate>
                <DataTemplate>
                            <Image Stretch="Fill" Height="60" Width="85" Source="{Binding Url}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

Page1 C# Code Behind: 后面的第1页C#代码:

 namespace Imaged
 {
  public partial class UserSubmitted : PhoneApplicationPage
  {
    private const string Myrssfeed = "http://feeds.bbci.co.uk/news/rss.xml";

    public UserSubmitted()
    {
        InitializeComponent();

        //This next function calls the RSS service, and returns the (items) and binds it to 
        //{listbox.ItemsSource = items;}. I am unable to reference the count of the items, or 
        //the array of it for some reason? The images load once the page loads.
        RssService.GetRssItems(Myrssfeed, (items) => { listbox.ItemsSource = items; }, (exception) => { MessageBox.Show(exception.Message); }, null);
    }     
   }
  }

Once the listbox fills I am now trying to pass the selection by the user to a pivot page. 列表框填满后,我现在尝试将用户的选择传递到数据透视页。 I want that same image to show up in the pivot, and when the user pivots left or right, it shows the previous image or next image in the collection. 我希望同一图像显示在枢轴中,并且当用户向左或向右旋转时,它会显示集合中的上一个图像或下一个图像。

The Pivot Page I am trying to pass this to, XAML: 我正在尝试将其传递给XAML的“数据透视页面”:

<Grid x:Name="LayoutRoot" Background="Transparent">
    <!--Pivot Control-->
    <controls:Pivot Title="{Binding Title}">

        <!--Pivot item one-->
        <controls:PivotItem x:Name="item1">
                <Image Source="{Binding Url}"/>  <!--I take it this is causing the pics to be the same?-->
        </controls:PivotItem>

        <!--Pivot item two-->
        <controls:PivotItem x:Name="item2">
                <Image Source="{Binding Url}"/>
        </controls:PivotItem>

        <!--Pivot item three-->
        <controls:PivotItem x:Name="item3">
                <Image Source="{Binding Url}"/>
        </controls:PivotItem>

    </controls:Pivot>
</Grid>

The RSS Service Class being called: RSS服务类被称为:

 namespace WindowsPhone.Helpers
 { 
  public class RssService
  {
    public static void GetRssItems(string rssFeed, Action<IList<RssItem>> onGetRssItemsCompleted = null, Action<Exception> onError = null, Action onFinally = null)
    {

        WebClient webClient = new WebClient();

        // register on download complete event
        webClient.OpenReadCompleted += delegate(object sender, OpenReadCompletedEventArgs e)
        {
            try
            {
                // convert rss result to model
                IList<RssItem> rssItems = new List<RssItem>();

                Stream stream = e.Result;
                XmlReader response = XmlReader.Create(stream);
                {
                    SyndicationFeed feeds = SyndicationFeed.Load(response);

                    foreach (SyndicationItem f in feeds.Items)
                    {
                        RssItem rssItem = new RssItem(f.Title.Text, f.Summary.Text, f.PublishDate.ToString(), f.Links[0].Uri.AbsoluteUri);
                        rssItems.Add(rssItem);
                    }
                }    

                // notify completed callback
                if (onGetRssItemsCompleted != null)
                {
                    onGetRssItemsCompleted(rssItems);
                }
            }
            finally
            {
                // notify finally callback
                if (onFinally != null)
                {
                    onFinally();
                }
            }
        };

        webClient.OpenReadAsync(new Uri(rssFeed));
     }
    }
  }

and finally the RSSItem Class: 最后是RSSItem类:

namespace WindowsPhone.Helpers
{
  public class RssItem
  {
    public RssItem(string title, string summary, string publishedDate, string url)
    {
        Title = title;
        Summary = summary;
        PublishedDate = publishedDate;
        Url = url;

        // Get plain text from html
        PlainSummary = HttpUtility.HtmlDecode(Regex.Replace(summary, "<[^>]+?>", ""));
    }
    public string Title { get; set; }
    public string Summary { get; set; }
    public string PublishedDate { get; set; }
    public string Url { get; set; }
    public string PlainSummary { get; set; }
    }
  }

Disclaimer: I don't think that binding this many items to a Pivot control is necessarily the right thing to do. 免责声明:我认为将这么多项目绑定到Pivot控件不一定是正确的事情。 Your mileage may vary, but I think a more virtualized solution would be more efficient. 您的里程可能会有所不同,但是我认为虚拟化解决方案会更有效。 For my tests, it seemed to perform OK, but my little voice tells me that there be dragons here... 对于我的测试,它似乎表现还可以,但是我的小声音告诉我,这里有龙……

I recreated your project to the best of my ability and made some enhancements to get it to do what you wanted. 我尽我所能重新创建了您的项目,并进行了一些增强以使其能够完成您想要的事情。 Basically, the trick was using a ViewModel that was shared between both the main list page (UserSubmitted.xaml) and the page with the Pivot items on it (PivotPage1.xaml). 基本上,窍门是使用在主列表页面(UserSubmitted.xaml)和上面带有Pivot项的页面(PivotPage1.xaml)之间共享的ViewModel。 By setting both page's DataContext property to the same object, we were able to bind both lists to the same source, thus eliminating the need to pass anything around. 通过将两个页面的DataContext属性设置为相同的对象,我们能够将两个列表绑定到相同的源,从而消除了传递任何内容的需要。

In App.xaml.cs: 在App.xaml.cs中:

public static ViewData ViewModel { get; private set; }

private void Application_Launching(object sender, LaunchingEventArgs e)
{
     // note: you should properly Tombstone this data to prevent unnecessary network access
     ViewModel = new ViewData();
}

Here is how ViewData is defined: 这是ViewData的定义方式:

public class ViewData : INotifyPropertyChanged
{
    private string _FeedTitle;
    private RssItem _SelectedItem = null;
    private ObservableCollection<RssItem> _feedItems = new ObservableCollection<RssItem>();

    private const string MyRssfeed = "http://feeds.bbci.co.uk/news/rss.xml";

    public ViewData()
    {
        RssService.GetRssItems(
            MyRssfeed,
            (title, items) =>
            {
                App.Current.RootVisual.Dispatcher.BeginInvoke(() =>
                {
                    FeedTitle = title;
                    FeedItems = new ObservableCollection<RssItem>(items);
                });
            },
            (exception) =>
            {
                MessageBox.Show(exception.Message);
            },
            null);
    }

    public ObservableCollection<RssItem> FeedItems
    {
        get { return _feedItems; }
        set
        {
            if (_feedItems == value)
                return;
            _feedItems = value;
            NotifyPropertyChanged(this, new PropertyChangedEventArgs("FeedItems"));
        }
    }

    public string FeedTitle
    {
        get { return _FeedTitle; }
        set
        {
            if (_FeedTitle == value)
                return;
            _FeedTitle = value;
            NotifyPropertyChanged(this, new PropertyChangedEventArgs("FeedTitle"));
        }
    }

    public RssItem SelectedItem
    {
        get { return _SelectedItem; }
        set
        {
            if (_SelectedItem == value)
                return;
            _SelectedItem = value;
            NotifyPropertyChanged(this, new PropertyChangedEventArgs("SelectedItem"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(object sender, PropertyChangedEventArgs args)
    {
        if (PropertyChanged != null)
            PropertyChanged(sender, args);
    }
}

Once this is established, it's relatively easy to wire up both page's data context properties to App.ViewModel. 一旦建立,将两个页面的数据上下文属性连接到App.ViewModel相对容易。

Last item was the scrolling and positioning of the selected item when navigating. 最后一项是导航时所选项目的滚动和定位。 When you select an item from the list page, the SelectedItem property of the shared ViewModel is bound to the SelectedItem property on the ListBox. 当您从列表页面选择一个项目时,共享ViewModel的SelectedItem属性绑定到ListBox上的SelectedItem属性。 After navigation to the details page, we have to find the selected item in the pivot and make it visible: 导航到详细信息页面后,我们必须在枢轴中找到选定的项目并使之可见:

public PivotPage1()
{
    InitializeComponent();
    Loaded += (sender, e) =>
        {
            this.DataContext = App.ViewModel;
            var selectedItem = App.ViewModel.SelectedItem;
            var pi = ItemPivot.Items.First(p => p == selectedItem);
            ItemPivot.SelectedItem = pi;
        };
}

Setting the SelectedItem property of the Pivot control scrolls the pivot to the proper item and makes it visible. 设置枢轴控件的SelectedItem属性会将枢轴滚动到适当的项目并使它可​​见。

The full sample is posted at http://chriskoenig.net/upload/imaged.zip if you want to see it in action. 如果您想查看完整的示例,请访问http://chriskoenig.net/upload/imaged.zip

If I got you correctly, you need to bind listbox in following way: 如果我正确理解了您,则需要通过以下方式绑定列表框:

<ListBox ItemsSource="{Binding items}" SelectedItem="{Binding SelectedFeed, Mode=TwoWay}" />

And then bind Pivot in same way: 然后以相同方式绑定Pivot:

<Pivot ItemsSource="{Binding items}" SelectedItem="{Binding SelectedFeed, Mode=TwoWay}" />

Try the following for the pivot (based on Alex's code) 尝试以下操作作为枢轴(基于Alex的代码)

<Pivot ItemsSource="{Binding items}" SelectedItem="{Binding SelectedFeed, Mode=TwoWay}">
    <Pivot.ItemTemplate>
            <DataTemplate>
                <Image Source="{Binding Url}"/>
            </DataTemplate>
        </Pivot.ItemTemplate>
</Pivot>

It assumes on the pivot page DataContext there is the same object "items" providing access to all the feeditems, and a property SelectedFeed which (as Alex mentioned) supports INotifyPropertyChanged 它假定在​​数据透视页DataContext上存在相同的对象“ items”,提供对所有供稿项的访问,并具有一个SelectedSelected属性(如Alex所述),它支持INotifyPropertyChanged

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 绑定到LongListSelector / Listbox的项目数据未在Windows Phone 8本地数据库中显示 - Items Data Binded to LongListSelector/Listbox not showing in windows phone 8 local database Windows Phone:“手动”刷新绑定的列表框 - Windows Phone: refresh a binded listbox “manually” Windows Phone 7通过上下文查询字符串将数据从列表框传递到另一个页面 - Windows Phone 7 passing data from listbox to another page via context query string 如何在Windows Phone 7中设置绑定到ListBox的具有不同数据模型的ListStyle的不同样式? - How to set different Style of ListBoxItem with different data model binded to the ListBox in Windows Phone 7? Windows Phone 7-从列表框中传递/传输所选数据 - Windows Phone 7 - Passing / transferring selected data from listbox Windows Phone 8:将数据从PHP页面传递到Windows Phone 8应用 - Windows Phone 8: passing data from PHP page to windows phone 8 app 列表框数据绑定 Windows Phone - Listbox Data Binding Windows Phone Windows Phone 8上的列表框中的数据绑定 - Data binding in ListBox on Windows Phone 8 为Windows Phone 8.1将数据从页面传递到页面 - Passing Data from Page to Page for Windows Phone 8.1 如何使用Windows Phone(Pivot和ListBox)进行嵌套数据绑定 - How todo nested Databinding with Windows Phone (Pivot and ListBox)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM