簡體   English   中英

如何使用 PopAsync 傳遞數據?

[英]How to pass data using PopAsync?

我有以下情況:我有一個應用程序,我想在其中使用特殊頁面創建筆記。 我有帶有 ObservableCollection NoteItems 的 VM,其中包含所有注釋。 當我想創建一個新筆記時,我向這個 ObservableCollection 添加一個新筆記並使用 BindingContext 傳遞這個新筆記

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

在編輯頁面中,我有一個輸入字段

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

,這是將他的文本與 NoteItem 的 Text 參數綁定。 問題是,如果我更改輸入字段中的文本,它不會自動應用於 NoteItem 的文本參數。 這就是為什么我想在關閉此 EditingPage(返回 MainPage)時傳遞此文本的原因。 所以問題是,如何將此 Text 參數傳遞給位於 VM 中的 NoteItems ObservableCollection 中的 NoteItem 元素。

更新。 位於 NoteItems 中的 NoteItem 的值不會改變

更新2。 我對 NoteItem 的值有誤,它已更改,但新值沒有顯示在 MainPage 上,這就是為什么我使用 INotifyPropertyChanged,但它沒有用。

這是注釋項目 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();
                }
            } 
        }

和 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>
'''

為了動態更新 UI,您的 model 必須實現INotifyPropertyChanged

public class NoteItem : INotifyPropertyChanged
{
  ...
}

簡單地添加PropertyChanged方法與實現INotifyPropertyChanged不同。 必須在class定義中添加接口,這樣綁定機制就知道你的class已經實現了

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM