OnPropertyChanged不更新UI

时间:2017-05-14 17:59:47

标签: c# wpf binding listbox propertychanged

该窗口包含一个ListBox和一个TextBlock,我的目的是在ListBox中选择更改时更新TextBlock。

我有这堂课:

Run options: --seed 40805
Finished in 0.046173s, 21.6575 runs/s, 21.6575 assertions/s.
rails aborted!
ArgumentError: wrong number of arguments (given 1, expected 0)
/usr/local/rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/test_unit/minitest_plugin.rb:9:in `aggregated_results'
/usr/local/rvm/gems/ruby-2.3.1/gems/minitest-5.10.2/lib/minitest.rb:597:in `report'

这是ViewModelBase:

class ViewModelMain : ViewModelBase
{
    public ObservableCollection<MemEntity> items { get; set; }
    public object SelectedItem 
    { 
        get
        {
            return _selectedItem;
        }
        set
        {
            _selectedItem = SelectedItem;
            OnPropertyChanged("SelectedItem");
        }
    }

    public object _selectedItem { get; set; }

    public ViewModelMain()
    {
        items = new ObservableCollection<MemEntity> {
        new MemEntity{s = "a", Correct = 2, Incorrect = 1},
        new MemEntity{s = "b"},
        new MemEntity{s = "c"}
        };
    }
}

观点:

class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

我以为我现在把所有东西放在盒子里,但是它不起作用。我做错了什么?

1 个答案:

答案 0 :(得分:2)

_selectedItem = SelectedItem;什么也没做。你有一个不使用value的setter。制作_selectedItem = value;

使用标准代码段创建具有支持私有字段的属性(具有concreate类型):

private MemEntity _selectedItem;
public MemEntity SelectedItem 
{ 
    get
    {
        return _selectedItem;
    }
    set
    {
        _selectedItem = value;
        OnPropertyChanged("SelectedItem");
    }
}