xamarin.formsnavigationxamarin.forms.entry

How to pass data using PopAsync?


I have the following situation: I have an app, where I want to create notes using a special page for it. I have VM with ObservableCollection NoteItems with all the notes. When I want to create a new note, I add a new note to this ObservableCollection and pass this new note using BindingContext

    var editingPage = new EditingPage();
    editingPage.BindingContext = NoteItems[NoteItems.Count - 1].Text; 
    Application.Current.MainPage.Navigation.PushAsync(editingPage);

In the editing page I have an Entry field

       <Entry
         x:Name="EdtingPageEntryField"
         Text="{Binding Text}"
         Placeholder="Enter a note"
       />

, which is Binding his text with the Text parameter of a NoteItem. The problem is that if I change the text in entry field, it does not automatically apply to a Text parameter of a NoteItem. That is why I want to pass this text when I close this EditingPage(go back to the MainPage). So the question is, how can I pass this Text parameter to a NoteItem element from NoteItems ObservableCollection, which is located in VM.

UPD. The value of NoteItem, which is located in NoteItems does not change

UPD2. I was wrong about the value of NoteItem, it has been changed, but the new value does not display on MainPage, that is why I used INotifyPropertyChanged, but it did not work.

Here is Note Item class

public class NoteItem
    {

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        private string text;
        public string Text 
        { 
            get { return text; } 
            set 
            { 
                if(text != value) 
                { 
                    text = value; 
                    NotifyPropertyChanged();
                }
            } 
        }

And MainPage.xaml:

<ContentPage.BindingContext>
        <local:NoteItemViewModel/>
    </ContentPage.BindingContext>

    <FlexLayout>
        
        <ListView ItemsSource="{Binding NoteItems}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Label Text="{Binding Text}"/>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        
    </FlexLayout>
'''

Solution

  • in order to dynamically update the UI, your model must implement INotifyPropertyChanged

    public class NoteItem : INotifyPropertyChanged
    {
      ...
    }
    

    simply adding a PropertyChanged method is not the same as implementing INotifyPropertyChanged. You must add the interface to the class definition so that the binding mechanism knows that your class has implemented it