Working with Pivot

我与影子孤独终老i 提交于 2019-12-13 05:57:30

问题


I am having 2 list.One list for pivot header and another for pivot item in a pivot control. I am unable to bind as such

Below is a .cs part.

public class ViewModel
{
    List<Feed> feeds = new List<Feed>();

    public ViewModel()
    {
        GetArticlesListingData();
    }

    public List<Feed> Feeds { get { return this.feeds; } }

    private async Task GetArticlesListingData()
    {
        try
        {
            for (var k = 0; k < 6; k++)
            {
                Feed feed1 = new Feed();
                feed1.Title = "National" + k;



                HttpRequestMessage request1 = new HttpRequestMessage(HttpMethod.Get, "FEEDURL");
                request1.Headers.Add("UserAgent", "Windows 8 app client");
                request1.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                request1.Headers.Add("Authorization", "bearer " + accessToken);

                HttpClient client1 = new HttpClient();
                HttpResponseMessage response1 = await client1.SendAsync(request1, HttpCompletionOption.ResponseHeadersRead);
                var result1 = await response1.Content.ReadAsStringAsync();
                result1 = Regex.Replace(result1, "<[^>]+>", string.Empty);
                var rootObject1 = JArray.Parse(result1);
                int mainitemsCount = rootObject1.Count();

                List<Article> articleList = new List<Article>();
                for (int i = 0; i < mainitemsCount; i++)
                {
                    string strHeadline = rootObject1[i]["HeadLine"].ToString();
                    articleList.Add(new Article
                    {
                        Title = rootObject1[i]["Abstract"].ToString(),
                        HeadLine = rootObject1[i]["HeadLine"].ToString()
                    });
                }

                feed1.Articles = articleList;
                feeds.Add(feed1);

            }
        }
        catch (Exception ex)
        {

        }
    }
}


public class Feed
{
    public string Title { get; set; }
    public List<Article> Articles { get; set; }
}

public class Article
{
    public string Title { get; set; }
    public string HeadLine { get; set; }
}

Below is my XAML part,

  <Page.Resources>
    <local:ViewModel x:Key="ViewModel" />
    <DataTemplate x:Key="headerTemplate">
        <TextBlock Text="{Binding Title}" />
    </DataTemplate>
    <DataTemplate x:Key="pivotTemplate">
        <ListView Name="ListBox" ItemsSource="{Binding Articles}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Title}" />
                        <TextBlock Text="{Binding HeadLine}"/>
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </DataTemplate>
</Page.Resources>

<Pivot DataContext="{StaticResource ViewModel}" x:Name="pivot" HeaderTemplate="{StaticResource headerTemplate}" ItemTemplate="{StaticResource pivotTemplate}" ItemsSource="{Binding Feeds}" ></Pivot>

Please guide me to solve this issue. I want to bind the data as below image in a pivot style


回答1:


Here is a working sample.

First, I have build a very basic View Model to store at the same time your menu entries and the articles. It is a list of Feed with a title (the menu entry) and a list of articles.

public class ViewModel : BindableBase
{
    ObservableCollection<Feed> feeds = new ObservableCollection<Feed>();

    public ViewModel()
    {

    }

    public async Task LoadFeeds()
    {
        var myFeeds = new ObservableCollection<Feed>();
        Feed feed1 = new Feed();
        feed1.Title = "Feed A";
        feed1.Articles = new List<Article>() { new Article() { Title = "Article 1", HeadLine = "Headline 1" },
        new Article() { Title = "Article 2", HeadLine = "Headline 2"},
        new Article() { Title = "Article 3", HeadLine = "Headline 3"}};
        myFeeds.Add(feed1);

        Feed feed2 = new Feed();
        feed2.Title = "Feed B";
        feed2.Articles = new List<Article>() { new Article() { Title = "Article 4", HeadLine = "Headline 4" } };
        myFeeds.Add(feed2);

        Feed feed3 = new Feed();
        feed3.Title = "Feed C";
        feed3.Articles = new List<Article>() { new Article() { Title = "Article 5", HeadLine = "Headline 5" },
        new Article() { Title = "Article 6", HeadLine = "Headline 6"}};
        myFeeds.Add(feed3);

        Feeds = myFeeds;
    }

    public ObservableCollection<Feed> Feeds
    {
        get { return this.feeds; }
        set
        {
            Set<ObservableCollection<Feed>>(ref this.feeds, value);
        }
    }
}

public class Feed
{
    public string Title { get; set; }
    public List<Article> Articles { get; set; }
}

public class Article
{
    public string Title { get; set; }
    public string HeadLine { get; set; }
}

public abstract class BindableBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public virtual bool Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
    {
        if (object.Equals(storage, value))
            return false;

        storage = value;
        this.RaisePropertyChanged(propertyName);
        return true;
    }

    public virtual void RaisePropertyChanged([CallerMemberName]string propertyName = null)
    {
        if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
            return;

        var handler = PropertyChanged;
        if (!object.Equals(handler, null))
        {
            var args = new PropertyChangedEventArgs(propertyName);
            handler.Invoke(this, args);

        }
    }
}

Add the following into your View codebehind:

protected async override void OnNavigatedTo(NavigationEventArgs e)
{
    var viewModel = pivot.DataContext as ViewModel;
    await viewModel.LoadFeeds();
}

And then, the XAML for the Pivot control. You need to specify the HeaderTemplate and the ItemTemplate.

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

    <Page.Resources>
        <local:ViewModel x:Key="ViewModel" />
        <DataTemplate x:Key="headerTemplate">
            <TextBlock Text="{Binding Title}" />
        </DataTemplate>
        <DataTemplate x:Key="pivotTemplate">
            <ListView Name="ListBox" ItemsSource="{Binding Articles}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <TextBlock Text="{Binding Title}" />
                            <TextBlock Text="{Binding HeadLine}"/>
                        </StackPanel>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </DataTemplate>
    </Page.Resources>

    <Pivot DataContext="{StaticResource ViewModel}" x:Name="pivot" HeaderTemplate="{StaticResource headerTemplate}" ItemTemplate="{StaticResource pivotTemplate}" ItemsSource="{Binding Feeds}" >
    </Pivot>
</Page>

The final result is:



来源:https://stackoverflow.com/questions/37741976/working-with-pivot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!