Wpf绑定属性未在双向模式下更新

时间:2016-08-07 10:52:49

标签: c# wpf xaml mvvm

我有简单的图库,其中包含注释和文本框,可以按标题添加新的图片。 我使用mvvm,其他绑定工作正确。 当我设置注释的标题并单击添加属性NewNote.Title更新并将对象保存在数据库中。之后我清除了NewNote.Title但UI没有更新。

这是简短视频https://youtu.be/l3vFwI-a4TQ

XAML

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

页面浏览模型

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();
    }
}

对象视图模型

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));
    }
}

1 个答案:

答案 0 :(得分:1)

在设置属性时,您没有在viewmodel上调用OnPropertyChanged

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));
    }
}

此外,应通过命令调用LoadNotes和AddNotes,新标题应作为参数发送。 https://msdn.microsoft.com/en-us/library/ms752308(v=vs.110).aspx