question

EduardoGomez-1870 avatar image
0 Votes"
EduardoGomez-1870 asked LeonLu-MSFT answered

display number of notes in a label

Hello

I have an issue, and I don't know how to tackle it.

A am using firebase, to save a list of Notebooks and Notes

I am currently displaying the name of each Notebook in a list

107304-notebooks.png

but I also want to display in a Label, how many notes I have in every notebook

For example:

I Have a WPF app, that I made, that create notebooks and notes, this get store in firebase

I currently have 2 notebooks

Notebook 1 has Notes 1 and Note 2
Notebook 2 has Note 1

How can I display it in a Label, how many notes the notebook has?
107267-screenshot-6.png

here is my VM

public class NotesVM {
        public ObservableCollection<Notebook> NotebooksCollection { get; set; }
        public ObservableCollection<Note> NotesCollection { get; set; }
        public ICommand CreateNewNotebook { get; set; }
        public ICommand SelectedNoteBookCommand { get; set; }

        public NotesVM() {
            NotebooksCollection = new ObservableCollection<Notebook>();
            NotesCollection = new ObservableCollection<Note>();
            CreateNewNotebook = new Command(async () => {
                Page app = Application.Current.MainPage;
                string result = await app.DisplayPromptAsync(string.Empty, "Notebook name?");
                Notebook notebook = new Notebook() { Name = result, UserId = App.UserId };
                await Database.InsertAsync(notebook);
                GetNotebooksAsync();
            });
            SelectedNoteBookCommand = new Command((parameter) => {
                var notebook = parameter as Notebook;
            });
            GetNotebooksAsync();
        }
        private async void GetNotebooksAsync() {
            var notebooks = await Database.ReadAsync<Notebook>();
            if (notebooks != null) {
                notebooks.Where(n => n.Id == App.UserId);
                NotebooksCollection.Clear();
                foreach (var item in notebooks) {
                    NotebooksCollection.Add(item);
                }

            }
        }
    }


and my db

private static readonly string FirebadeDb = "https://safe-wpf-default-rtdb.europe-west1.firebasedatabase.app/";

        public static async Task<bool> InsertAsync<T>(T Item) {

            string jsonBody = JsonConvert.SerializeObject(Item);
            var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
            using (HttpClient client = new HttpClient()) {
                var res = await client.PostAsync($"{FirebadeDb}{Item.GetType().Name.ToLower()}.json", content);
                if (res.IsSuccessStatusCode) {
                    return true;
                } else {
                    return false;
                }
            }
        }

        public static async Task<List<T>> ReadAsync<T>() where T : HasId {

            using (HttpClient client = new HttpClient ()) {
                var res = await client.GetAsync($"{FirebadeDb}{typeof(T).Name.ToLower()}.json");
                var JsonRes = await res.Content.ReadAsStringAsync();
                if (res.IsSuccessStatusCode) {
                    var valuePairs = JsonConvert.DeserializeObject<Dictionary<string, T>>(JsonRes);
                    if (valuePairs != null) {
                        List<T> objts = new List<T>();
                        foreach (var item in valuePairs) {

                            item.Value.Id = item.Key;
                            objts.Add(item.Value);
                        }
                        return objts;
                    }

                } else {
                    return null;
                }

                return null;
            }
        }

        public static async Task<bool> UpdateAsync<T>(T Item) where T : HasId {

            string jsonBody = JsonConvert.SerializeObject(Item);
            var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
            using (HttpClient client = new HttpClient()) {
                var res = await client.PutAsync($"{FirebadeDb}{Item.GetType().Name.ToLower()}/{Item.Id}.json",
                    content);
                if (res.IsSuccessStatusCode) {
                    return true;
                } else {
                    return false;
                }
            }
        }

        public static async Task<bool> DeleteAsync<T>(T Item) where T : HasId {

            using (HttpClient client = new HttpClient()) {
                var res = await client.DeleteAsync
                    ($"{FirebadeDb}{Item.GetType().Name.ToLower()}/{Item.Id}.json");
                if (res.IsSuccessStatusCode) {
                    return true;
                } else {
                    return false;
                }
            }
        }
    }
}


dotnet-xamarin
notebooks.png (71.1 KiB)
screenshot-6.png (604.4 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

LeonLu-MSFT avatar image
0 Votes"
LeonLu-MSFT answered

Hello,​

Welcome to our Microsoft Q&A platform!

I notice you use ObservableCollection to contains data, it seems that you have lots of data in it, So I do not recommend you to use Label to display all of data. Please use CollectionView to achieve it like this article.

https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/collectionview/grouping

I create a demo to test it. Here is running screenshot.

107441-image.png


Here is my layout's XAML code.

<StackLayout>
        <CollectionView ItemsSource="{Binding NotebooksCollection}"
                IsGrouped="true">
          
            <CollectionView.GroupHeaderTemplate>
                <DataTemplate>
                    <Label Text="{Binding Name}"
                   BackgroundColor="LightGray"
                
                   FontAttributes="Bold" />
                </DataTemplate>
            </CollectionView.GroupHeaderTemplate>


            <CollectionView.ItemTemplate>
                <DataTemplate>

                    <StackLayout Orientation="Vertical">                       
                        <Label 
                       Text="{Binding Item1}"
                       FontAttributes="Bold" />
                        <Label 
                       Text="{Binding Item2}"
                       FontAttributes="Bold"
                       />
                        <Label 
                       Text="{Binding Item3}"
                       FontAttributes="Bold"
                       />
                    </StackLayout>

                </DataTemplate>
            </CollectionView.ItemTemplate>
            
        </CollectionView>
    </StackLayout>


Here is layout's background code.

public MainPage()
        {
            InitializeComponent();

            BindingContext = new NotesVM();
        }


Here is test NotesVM.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Windows.Input;
using Xamarin.Forms;

namespace App106
{
    class NotesVM
    {
        public ObservableCollection<Notebook> NotebooksCollection { get; set; }
        public ObservableCollection<Note> NotesCollection { get; set; }
        public ICommand CreateNewNotebook { get; set; }
        public ICommand SelectedNoteBookCommand { get; set; }
        public NotesVM()
        {
            NotebooksCollection = new ObservableCollection<Notebook>();
            NotesCollection = new ObservableCollection<Note>();
            //CreateNewNotebook = new Command(async () => {
            //    Page app = Application.Current.MainPage;
            //    string result = await app.DisplayPromptAsync(string.Empty, "Notebook name?");
            //    Notebook notebook = new Notebook() { Name = result, UserId = App.UserId };
            //    await Database.InsertAsync(notebook);
            //    GetNotebooksAsync();
            //});
            //SelectedNoteBookCommand = new Command((parameter) => {
            //    var notebook = parameter as Notebook;
            //});
            GetNotebooksAsync();
        }
        private async void GetNotebooksAsync()
        {

            NotebooksCollection.Add(new Notebook("NoteBook1", "1", new ObservableCollection<Note>() { new Note() { Item1 = "item1", Item2 = "item2", Item3 = "item3" } } ));

            NotebooksCollection.Add(new Notebook("NoteBook2", "2", new ObservableCollection<Note>() { new Note() { Item1 = "item1", Item2 = "item2", Item3 = "item3" } }));
            NotebooksCollection.Add(new Notebook("NoteBook3", "3", new ObservableCollection<Note>() { new Note() { Item1 = "item1", Item2 = "item2", Item3 = "item3" } }));
        
            //var notebooks = await Database.ReadAsync<Notebook>();
            //if (notebooks != null)
            //{
            //    notebooks.Where(n => n.Id == App.UserId);
            //    NotebooksCollection.Clear();
            //    foreach (var item in notebooks)
            //    {
            //        NotebooksCollection.Add(item);
            //    }
            //}
        }
    }

    public class Note
    {
      //  public string NotebookName { get; set; }

        public string Item1 { get; set; }
        public string Item2 { get; set; }

        public string Item3 { get; set; }
    }

    public class Notebook: ObservableCollection<Note>
    {
        public string Name { get; set; }
        public string UserId { get; set; }

        public Notebook(string name, string userId, ObservableCollection<Note> Notes):base(Notes)
        {
            Name = name;
            UserId= userId;
        }
    }
}



Best Regards,

Leon Lu



If the response is helpful, please click "Accept Answer" and upvote it.

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.



image.png (20.7 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.