触发RaisePropertyChangedEvent后ListView未更新,附相关XAML代码
看起来你碰到了WPF绑定里常见的UI不刷新问题,我帮你梳理几个最可能的原因和解决办法,一步步排查:
首先确认ViewModel的INotifyPropertyChanged实现是否正确
你的ViewModel必须实现INotifyPropertyChanged接口,而且在属性的setter里要准确调用RaisePropertyChanged,还要注意属性名称不能写错(推荐用nameof()避免拼写错误)。示例代码:public class YourViewModel : INotifyPropertyChanged { private string _playerFirstName; public string PlayerFirstName { get => _playerFirstName; set { if (_playerFirstName != value) { _playerFirstName = value; RaisePropertyChanged(nameof(PlayerFirstName)); } } } public event PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }如果
RaisePropertyChanged传的属性名和绑定的属性不匹配,UI肯定不会响应更新。检查ListView的ItemsSource绑定是否用了ObservableCollection
普通的List<T>不会自动通知集合变化,必须用ObservableCollection<T>作为ListView的数据源,它会在集合添加/删除/修改元素时自动触发UI更新。比如:public ObservableCollection<Player> Players { get; } = new ObservableCollection<Player>();对应的XAML绑定要确保指向这个集合:
<ListView ItemsSource="{Binding Players}" > <!-- 你的ItemTemplate定义 --> </ListView>确认集合中的实体类也实现了INotifyPropertyChanged
如果你是更新集合里单个Player对象的属性(比如FirstName/LastName),那Player类本身也需要实现INotifyPropertyChanged接口。不然就算ViewModel触发了事件,UI也不知道实体的属性变了:public class Player : INotifyPropertyChanged { private string _firstName; public string FirstName { get => _firstName; set { if (_firstName != value) { _firstName = value; RaisePropertyChanged(nameof(FirstName)); } } } // 实现INotifyPropertyChanged接口的其余代码 public event PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }验证DataContext是否正确设置
确保你的View的DataContext已经绑定到了ViewModel的实例。可以在View的构造函数里直接赋值:public YourView() { InitializeComponent(); DataContext = new YourViewModel(); }或者通过XAML资源的方式绑定,只要保证DataContext没有断链,绑定的属性能被UI找到就行。
检查TextBox的绑定更新时机(可选)
如果你希望输入TextBox时实时更新ViewModel的属性,可以设置UpdateSourceTrigger=PropertyChanged,默认是LostFocus时才更新源:<TextBox Text="{Binding PlayerFirstName, UpdateSourceTrigger=PropertyChanged}" .../>
按这个顺序排查下来,应该能找到问题所在。
内容的提问来源于stack exchange,提问作者jDave1984

