1. 描述:
绑定属性中,基础类型比如string,setProperty可以实现实时刷新;但 List<string>就不会。
2. 原因:
View与ViewModel中做绑定时,对于基础类型的绑定属性,在Set方法中用SetProperty() 便可以实现View中的实时刷新。(因为ViewModel继承ObservableObject,所以可以使用SetProperty,里面实现了OnPropertyChanged,即属性改变,会立即更新到View中);
如果是List<>,则不具备。可以用ObservableCollection替换List,因为它继承INotifyPropertyChanged,也实现了通知。
3. 解决:
用ObservableCollection替换List,即写成 ObservableCollection<string>.
4. 示例:
public string? ModelNameSearch
{
get => _modelNameSearch;
set => SetProperty(ref _modelNameSearch, value);
}
public ObservableCollection<string> ModelList
{
get => _modelList;
set => _modelList = value;
}