該窗口包含一個ListBox和一個TextBlock,我的目的是在ListBox中的選擇更改時更新TextBlock。OnPropertyChanged不更新UI
我有這個類:
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"}
};
}
}
這是ViewModelBase:
class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
的觀點:
<ListBox x:Name="items" SelectedItem="{Binding SelectedItem}" ItemsSource="{Binding items}" DisplayMemberPath="s"/>
<TextBlock Text="{Binding SelectedItem.s}"/>
我想我現在已經在盒子的一切,但它不工作。我究竟做錯了什麼?
'_selectedItem =的SelectedItem;'什麼都不做。你有一個不使用'value'的setter。設置'_selectedItem = value;' – ASh
嘗試設置綁定模式爲雙向selectedItem –