c# - ObservableCollection 似乎不保存添加的项目

c# - ObservableCollection doesn't seem save added items

描述

我正在尝试构建这个简单的 UWP MVVM 笔记应用程序。 该应用程序的目的是将文本从 Textbox 添加到 ListView,当 Add Button 被单击,或通过按 Delete Button 删除 ListView 的项目,它被分配给每个ListView.

中的项目

正在将项目添加到 ObservableCollection

ObservableCollection<Note> 添加项目似乎工作正常。 ListView 中显示的项目没有任何问题。

删除 ObservableCollection 中的项目

无法正常删除项目。

我的调试尝试

我试图调用负责从构造函数和 Delete Button 中删除项目的方法。 当我从 Delete Button 调用 DoDeleteNote(Note itemToDelete) 时,没有任何反应,但是如果我从构造函数调用相同的方法然后该项目被删除。

我在 DoDeleteNote(Note itemToDelete) 方法中创建了一个断点,我可以在调试器中看到它运行了代码,但没有从 ObservableCollection<Note> 中删除任何内容。 但是,当我从构造函数调用 DoDeleteNote(Note itemToDelete) 方法时,该项目被删除。

同样奇怪的是,我从 NoteViewModel 构造函数创建并添加到 ObservableCollection<Note>Note 项是ObservableCollection<Note> 中唯一的项目。我使用 Add Button 添加的项目已经消失,但仍显示在 ListView.

我在想 INotifyPropertyChanged 或绑定可能有问题,但我不确定从哪里开始寻找以及寻找什么,所以我需要一些帮助。

我知道这里似乎有很多代码,但我觉得有必要不遗漏任何东西来理解数据流。

XAML

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

    <Grid.DataContext>
        <viewModel:NoteViewModel/>
    </Grid.DataContext>

    <ListView  Header="Notes"
               HorizontalAlignment="Left" 
               Height="341"
               Width="228"
               VerticalAlignment="Top"
               Margin="163,208,0,0"
               ItemsSource="{Binding Notes, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">

        <ListView.ItemTemplate>
            <DataTemplate x:Name="MyDataTemplate">
                <StackPanel Orientation="Horizontal">

                    <TextBlock x:Name="TbxblListItem" Text="{Binding NoteText}"/>

                    <Button Command="{Binding DeleteNoteCommand}" 
                            CommandParameter="{Binding ElementName=TbxblListItem}">
                        <Button.DataContext>
                            <viewModel:NoteViewModel/>
                        </Button.DataContext>
                        <Button.Content>
                            <SymbolIcon Symbol="Delete" 
                                        ToolTipService.ToolTip="Delete Note" 
                                        HorizontalAlignment="Center" 
                                        VerticalAlignment="Center"/>
                        </Button.Content>
                    </Button>

                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

    <TextBox x:Name="TbxNoteContent" HorizontalAlignment="Left"
             Margin="571,147,0,0"
             TextWrapping="Wrap"
             VerticalAlignment="Top"
             Width="376"/>

    <Button Content="Add"
            HorizontalAlignment="Left"
            Margin="597,249,0,0"
            VerticalAlignment="Top"
            Command="{Binding AddNoteCommand}"
            CommandParameter="{Binding Text, ElementName=TbxNoteContent}"/>
</Grid>
</page>        

备注

namespace ListView2.Model
{
    class Note
    {
        private string _noteText;

        public Note(string noteText)
        {
            NoteText = noteText;
        }

        public string NoteText { get { return _noteText; } set { _noteText = value; } }
    }
}

通知

using System.ComponentModel;

namespace ListView2.Model
{
    class Notification : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

NoteViewModel

using System.Collections.ObjectModel;
using Windows.UI.Xaml.Controls;
using ListView2.Model;

namespace ListView2.ViewModel
{
    class NoteViewModel : Notification
    {
        #region Instance Fields
        private ObservableCollection<Note> _notes;
        private RelayCommand _addNoteCommand;
        private RelayCommand _deleteNoteCommand;
        //private string _noteText;
        #endregion

        #region Constructors
        public NoteViewModel()
        {
            //adds sample data to Notes property (ObservableCollection<Note>)
            Notes = new ObservableCollection<Note>() { new Note("Sample text 1"), new Note("Sample text 2") };

            //Used for testing the deletion of items from ObservableCollection-------------------------------------
            Notes.RemoveAt(1);
            Notes.Add(new Note("Sample text 3"));
            //foreach (var item in Notes)
            //{
            //    if (item.NoteText == "Sample text 3")
            //    {
            //        DoDeleteNote(item);
            //        break;
            //    }
            //}
            //------------------------------------------------------

            //Button command methods are added to delegates
            AddNoteCommand = new RelayCommand(DoAddNote);
            DeleteNoteCommand = new RelayCommand(DoDeleteNote);
        }
        #endregion

        #region Properties
        public ObservableCollection<Note> Notes { get { return _notes; } set { _notes = value; OnPropertyChanged("Notes"); } }

        //public string NoteText { get { return _noteText; } set { _noteText = value; OnPropertyChanged("NoteText"); } }

        public RelayCommand AddNoteCommand { get { return _addNoteCommand; } set { _addNoteCommand = value; } }

        public RelayCommand DeleteNoteCommand { get { return _deleteNoteCommand; } set { _deleteNoteCommand = value; } }

        #endregion

        #region methods

        private void DoAddNote(object obj)
        {
            var newItem = obj as string;
            if (!string.IsNullOrEmpty(newItem))
            {
                AddNote(newItem);
            }
        }

        //Work in progress
        private void DoDeleteNote(object obj)
        {
            //Used when the XAML Delete Button invokes this method
            TextBlock textBlockSender = obj as TextBlock;
            //string myString = textBlockSender.Text;
            Note itemToDelete = textBlockSender.DataContext as Note;

            //Used when the constuctor invokes this method, for testing purposes------------
            //Note itemToDelete = obj as Note;
            //--------------------------------------------------------

            foreach (Note note in this.Notes)
            {
                if (note.NoteText == itemToDelete.NoteText)
                {
                    //int noteIndex = Notes.IndexOf(note);
                    //Notes.RemoveAt(noteIndex);
                    DeleteNote(note);
                    break;
                }
            }
            //if (Notes.Contains(itemToDelete))
            //{
            //    Notes.Remove(itemToDelete);
            //}
        }

        public void AddNote(string noteText)
        {
            this.Notes.Add(new Note(noteText));
        }

        public void DeleteNote(Note itemToDelete)
        {
            this.Notes.Remove(itemToDelete);
        }
        #endregion
    }
}

RelayCommand class ICommand 的实现似乎与这个问题无关,所以我没有把它包括在这里,但如果你好奇它可以在 GitHub[ 上看到=34=]

正如@Eugene Podskal 指出的问题之一是这段代码

<Button.DataContext>
    <viewModel:NoteViewModel/>
</Button.DataContext>

您的 Layout Grid 实例化了一个新的 NoteViewModel,上面的代码将做同样的事情,让您在页面上留下 2 个活动的 NoteViewModel。

首先给ListView起个名字

<ListView x:Name="MyList" Header="Notes"

接下来让我们修复 ListView DataTemplate 上的绑定 MyList

<ListView.ItemTemplate>
   <DataTemplate x:Name="MyDataTemplate">
      <StackPanel Orientation="Horizontal">
         <TextBlock x:Name="TbxblListItem" Text="{Binding NoteText}"/>
         <Button Command="{Binding DataContext.DeleteNoteCommand, ElementName=MyList}" 
            CommandParameter="{Binding}">                            
         <SymbolIcon Symbol="Delete" 
            ToolTipService.ToolTip="Delete Note" 
            HorizontalAlignment="Center" 
            VerticalAlignment="Center"/>
        </Button>
     </StackPanel>
  </DataTemplate>
</ListView.ItemTemplate>

这一行

Command="{Binding DataContext.DeleteNoteCommand, ElementName=MyList}"

意味着我们现在绑定到 MyListDataContext,这是您在主 Grid

下定义的 NoteViewModel

CommandParamter简化为

CommandParameter="{Binding}"

正如我在下面解释的那样,更好的做法是绑定到 MyList 中的对象,在本例中是 Note

的对象

为了完成这项工作,我们需要稍微调整您的 NoteViewModel 将您的私人删除字段和 public 属性 更改为

private RelayCommand<Note> _deleteNoteCommand;
public RelayCommand<Note> DeleteNoteCommand { get { return _deleteNoteCommand; } set { _deleteNoteCommand = value; } }

并在构造函数中

DeleteNoteCommand = new RelayCommand<Note>(DoDeleteNote);

DoDeleteNote 方法简化为

private void DoDeleteNote(Note note)
{
    this.Notes.Remove(note);    
}

所以我们可以轻松地摆脱 TextBlock 的转换。您现在可以删除 DeleteNote 方法,因为它不再需要了。

最后,我们需要添加一个新的 RelayCommand,它采用通用类型以使我们的命令 DeleteNoteCommand 正常工作。

中继命令

public class RelayCommand<T> : ICommand
{
    #region Fields

    private readonly Action<T> _execute = null;
    private readonly Predicate<T> _canExecute = null;

    #endregion

    #region Constructors

    /// <summary>
    /// Creates a new command that can always execute.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    public RelayCommand(Action<T> execute)
            : this(execute, null)
    {
    }

    /// <summary>
    /// Creates a new command with conditional execution.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    /// <param name="canExecute">The execution status logic.</param>
    public RelayCommand(Action<T> execute, Predicate<T> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");

        _execute = execute;
        _canExecute = canExecute;
    }

    #endregion

    #region ICommand Members

    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute((T)parameter);
    }

    public event EventHandler CanExecuteChanged;

    public void RaiseCanExecuteChanged()
    {
        var handler = CanExecuteChanged;
        if (handler != null)
            CanExecuteChanged(this, new EventArgs());
    }


    public void Execute(object parameter)
    {
        _execute((T)parameter);
    }

    #endregion
}

抱歉,这个答案很长,但我想指出每一步。我还建议在使用 xaml 时使用 mvvm 框架,因为它会让你的生活更轻松。我推荐 mvvmlight 但还有很多其他的。希望有帮助