Rui Huang
Rui Huang

Reputation: 382

Add Item to ObservableCollection

I have one TextBox which the Text content has data binding to the View Model. I need to save different string from the TextBox to one collection, but seems it always replicates the last current TextBox's text to all the items. Although each time i have typed different text.

Here is the code in XAML:

<TextBox HorizontalAlignment="Left"
                 Background="Transparent"
                 Margin="0,81,0,0" 
                 TextWrapping="Wrap" 
                 Text="{Binding Note.NoteTitle, Mode=TwoWay}" 
                 VerticalAlignment="Top" 
                 Height="50" Width="380" 
                 Foreground="#FFB0AEAE" FontSize="26"/>

and in the View Model, I have:

public Note Note 
{
    get { return _note; }
    set { Set(() => Note, ref _note, value); }
}

private ObservableCollection<Note> _notes;

public async void AddNote(Note note)
{
    System.Diagnostics.Debug.WriteLine("AddNote Called...");
    _notes.Add(note);
}

There is one button in my page, and when click it, it will call AddNote.

Is there a solution i can save different items into _notes?

Edit: More information: The reason AddNote to be async is I need to call another task inside to save the note data:

private async Task saveNoteDataAsync()
{
  var jsonSerializer = new DataContractJsonSerializer(typeof(ObservableCollection<Note>));
  using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(fileName,
      CreationCollisionOption.ReplaceExisting))
  {
    jsonSerializer.WriteObject(stream, _notes);
  }
}

Upvotes: 0

Views: 3353

Answers (1)

VidasV
VidasV

Reputation: 4895

You are trying to push the same instance of Note object again and again. AddNote command should accept only string argument and create a new note before adding.

<TextBox HorizontalAlignment="Left"
                 Background="Transparent"
                 Margin="0,81,0,0" 
                 TextWrapping="Wrap" 
                 Text="{Binding NoteTitle, Mode=TwoWay}" 
                 VerticalAlignment="Top" 
                 Height="50" Width="380" 
                 Foreground="#FFB0AEAE" FontSize="26"/>

private string _NoteTitle;
public string NoteTitle
{
    get { return _NoteTitle; }
    set { _NoteTitle= value; }
}

private ObservableCollection<Note> _notes;

public async void AddNote(string NoteName)
{
    System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
    {
        System.Diagnostics.Debug.WriteLine("AddNote Called...");
        _notes.Add(new Note() {NoteTitle = NoteName});
    });
    // your async calls etc.
}

Upvotes: 2

Related Questions