Jan Kowalski Jan Kowalski - 3 months ago 12
C# Question

Wpf binded property not updating in 2-way-mode

I have simple gallery with notes and text box to add new one by title.
I use mvvm, other bindings work correcty.
When I set title of note and click add property NewNote.Title is updated and object saved in database. After that I clear NewNote.Title but UI is not updated.

here is short video https://youtu.be/l3vFwI-a4TQ

xaml

<TextBox Text="{Binding NewNote.Title}" />


page view model

class NotesPageViewModel : INotifyPropertyChanged
{
public ObservableCollection<NoteViewModel> Notes { get; set; }
public NoteViewModel NewNote { get; set; }

public NotesPageViewModel()
{
NewNote = new NoteViewModel();
}

public event PropertyChangedEventHandler PropertyChanged;

protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

internal void LoadNotes()
{
using (var uow = new UnitOfWork())
{
Notes.Clear();
uow.NotesRepository.OrderBy(n => n.Position).ToList()
.ForEach(note => Notes.Add((NoteViewModel)note));
}
}

internal void AddNote()
{
if (string.IsNullOrWhiteSpace(NewNote.Title))
return;

using (var uow = new UnitOfWork())
{
uow.NotesRepository.Add((Note)NewNote);
uow.Complete();
}
NewNote.Title = "";
LoadNotes();
}
}


object view model

class NoteViewModel : INotifyPropertyChanged
{
public int Id { get; set; }
public string Title { get; set; }

public event PropertyChangedEventHandler PropertyChanged;

protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}

Answer

You're not calling the OnPropertyChanged on the viewmodel when you're setting the property

class NoteViewModel : INotifyPropertyChanged
{
    private int _id;

    public int Id
    {
        get { return _id; }
        set
        {
            _id = value;
            OnPropertyChanged("Id");
        }
    }

    private string _title;

    public string Title
    {
        get { return _title; }
        set
        {
            _title = value;
            OnPropertyChanged("Title");
        }
    }


    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Also, the LoadNotes and AddNotes should be called via a command, and the new title should be sent as a parameter. https://msdn.microsoft.com/en-us/library/ms752308(v=vs.110).aspx

Comments