Share via

View Model comunicate

Eduardo Gomez 4,316 Reputation points
2021-07-20T21:35:34.45+00:00

Hello

I am trying to improve my note app, for my final project for school.

I am trying to communicate VMs but I am using the messaging center, but it is kind of slow

This is my Notebook VM

 public NotebooksVM() {  
  
            NotebooksCollection = new ObservableCollection<Notebook>();  
  
            SelectedNoteBookCommand = new Command(async () => {  
                await Application.Current.MainPage.Navigation.PushAsync(new NotesPage());  
                MessagingCenter.Send(this, "data", SelectedNotebook);  
                SelectedNotebook = null;  
  
            });  
            ChangeLayoutCommand = new Command(OnChangeLayout);  
        }  
  
  
        private async Task CreateNote() {  
            var result = await Application.Current.MainPage.DisplayPromptAsync(string.Empty,  
                "Notebook name?");  
  
            if (!string.IsNullOrEmpty(result)) {  
                var notebook = new Notebook() {  
                    Name = result,  
                    UserId = App.UserId,  
                    CreatedAt = DateTime.Now.ToString("ddd, MMMM yyyy")  
                };  
                await Database.InsertAsync(notebook);  
                GetNotebooksAsync();  
                await Application.Current.MainPage.Navigation.PushAsync(new NotesPage());  
                MessagingCenter.Send(this, "data", result);  
            } else {  
                return;  
            }  
        }  

As you can see in both cases I am sending the Notebook (Selected or New One) to the new Notes VM, So I can get all the notes from that notebook

Notes VM

public Notebook RecivedNotebook { get; set; }  
        public LayoutBase LayoutBase { get; set; }  
        public Note SelectedNote { get; set; }  
        public ICommand SelectedNoteCommand { get; set; }  
        public FontImageSource Glyph { get; set; }  
        public NotesVM() {  
  
            Glyph = new FontImageSource() {  
                Glyph = IconFonts.FormatListBulleted,  
                FontFamily = "material",  
                Size = 44  
            };  
  
            LayoutBase = new LinearLayout();  
  
            NotesCollection = new ObservableCollection<Note>();  
  
            CreateNewNoteCommand = new Command(async () => {  
                var note = await CreateNote(RecivedNotebook);  
                await Application.Current.MainPage.Navigation.PushAsync(new EditorPage());  
                MessagingCenter.Send(this, "note", note);  
                await GetNotes(RecivedNotebook);  
            });  
  
            SelectedNoteCommand = new Command(async () => {  
                await Application.Current.MainPage.Navigation.PushAsync(new EditorPage());  
                MessagingCenter.Send(this, "note", SelectedNote);  
                SelectedNote = null;  
  
            });  
  
            MessagingCenter.Subscribe<NotebooksVM, Notebook>(this, "data",  
            async (sender, data) => {  
                RecivedNotebook = data;  
                await GetNotes(RecivedNotebook);  
            });  
  
            ChangeLayoutCommand = new Command(OnChangeLayout);  
        }  
  
        private async Task GetNotes(Notebook notebook) {  
            var notes = await Database.ReadAsync<Note>();  
            if (notes != null) {  
                var newNotes = notes.Where(n => n.NotebookId == notebook.Id);  
                NotesCollection.Clear();  
                foreach (var item in newNotes) {  
                    NotesCollection.Add(item);  
                }  
            }  
        }  
  
        private async Task<Note> CreateNote(Notebook recivedNotebook) {  
  
            var result = await Application.Current.MainPage.DisplayPromptAsync(string.Empty,  
                 "Note name?");  
  
            if (!string.IsNullOrEmpty(result)) {  
                var note = new Note() {  
                    NotebookId = recivedNotebook.Id,  
                    Title = result,  
                    CreatedAt = DateTime.Now.ToString("ddd, MMMM yyyy")  
                };  
                await Database.InsertAsync(note);  
                return note;  
  
            } else {  
                return null;  
            }  

As you can see, y receive the note, using the messeging center, and send it again to another VM

 public Note RecivedNote { get; set; }  
        public EditorVM() {  
  
            SaveContent = new Command(() => { UpdateNote(); });  
            MessagingCenter.Subscribe<NotesVM, Note>(this, "note", (obj, item) => {  
                RecivedNote = item;  
            });  
        }  

So I was trying to figure out, how to do this without the messaging center and ZERO code-behind

This is my project if someone wants to see it
'
https://github.com/eduardoagr/safe.Xamarin/tree/main/Safe

By the way, any features or suggestions are welcome

@Wenyan Zhang (Shanghai Wicresoft Co,.Ltd.)

Developer technologies | .NET | Xamarin
0 comments No comments

Answer accepted by question author

Wenyan Zhang (Shanghai Wicresoft Co,.Ltd.) 36,456 Reputation points Microsoft External Staff
2021-07-21T09:27:59.087+00:00

Hello,
Welcome to our Microsoft Q&A platform!

You can use Action instead of MessageCenter. It also can achieve ZERO code-behind.
You can have a try with following code:

NotebooksVM

SelectedNoteBookCommand = new Command(async () => {  
                NotesPage notesPage = new NotesPage();  
                await Application.Current.MainPage.Navigation.PushAsync(notesPage);  
                NotesVM notesViewModel = (NotesVM)notesPage.BindingContext;  
                notesViewModel.RecivedNoteAction(SelectedNotebook);//invoke the action  
  
                //MessagingCenter.Send(this, "data", SelectedNotebook);  
                SelectedNotebook = null;  
  
            });  

NotesVM

CreateNewNoteCommand = new Command(async () => {  
                var note = await CreateNote(RecivedNotebook);  
                await GetNotes(RecivedNotebook);  
                EditorPage editorPage = new EditorPage();  
                await Application.Current.MainPage.Navigation.PushAsync(editorPage);  
                EditorVM Editor = (EditorVM)editorPage.BindingContext;  
                Editor.RecivedNoteAction(note);//Replace MessagingCenter.Send  
            });  
  
SelectedNoteCommand = new Command(async () => {  
                EditorPage editorPage = new EditorPage();  
                await Application.Current.MainPage.Navigation.PushAsync(editorPage);  
                EditorVM Editor = (EditorVM)editorPage.BindingContext;  
                Editor.RecivedNoteAction(SelectedNote);  
                //MessagingCenter.Send(this, "note", SelectedNote);  
                SelectedNote = null;  
  
            });  
// Replace  MessagingCenter.Subscribe  
RecivedNoteAction = async(Notebook) =>  
            {  
                RecivedNotebook = Notebook;  
                await GetNotes(RecivedNotebook);  
            };  

EditorVM

 public class EditorVM {  
        public string Text { get; set; }  
        public ICommand SaveContent { get; set; }  
        public Note RecivedNote { get; set; }  
        public Action<Note> RecivedNoteAction;  
        public EditorVM() {  
  
            SaveContent = new Command(() => { UpdateNote(); });  
  
            RecivedNoteAction = (Note) =>  
            {  
                RecivedNote = Note;    
            };  
        }  
  
        private void UpdateNote() {  
            // test  out of action function  
            Console.WriteLine("test------------{0}", this.RecivedNote.Title);  
        }  
    }  

Best Regards,
Wenyan Zhang


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.

Was this answer helpful?

0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.