INotifyPropertyChanged引发应用崩溃,如何正确实现x:Bind更新功能?
UWP中GridView选中图片透明度不更新且应用崩溃的解决办法
核心崩溃原因:无限递归的属性Getter
你的WorkingImage类中opacity属性的getter直接返回this.opacity,这会触发无限递归调用,导致栈溢出,直接引发应用崩溃,这也是构造对象时就崩溃的根本原因。
修复步骤
1. 修复opacity属性的递归问题
给属性添加私有字段存储值,避免直接访问自身造成递归:
namespace myProject.Classes { public class WorkingImage : WorkingFile, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; // 私有字段存储透明度值 private double _opacity; // 遵循C# PascalCase命名规范,修改属性名为首字母大写 public double Opacity { get { return _opacity; } set { if (value != _opacity) { _opacity = value; NotifyPropertyChanged(); } } } // 将bmpSource改为属性并实现变更通知(后续更新图片源时UI会自动刷新) private BitmapSource _bmpSource; public BitmapSource BmpSource { get => _bmpSource; set { if (_bmpSource != value) { _bmpSource = value; NotifyPropertyChanged(); } } } public WorkingImage(StorageFile inFile) : base(inFile) { // base(inFile)已调用父类构造处理文件赋值,无需重复设置base.file Opacity = 1; } private void NotifyPropertyChanged([CallerMemberName] string propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public void Select() { Opacity = 0.5; } public void Deselect() { Opacity = 1; } } }
2. 更新XAML中的绑定
属性名已改为Opacity(首字母大写),同步修改XAML绑定:
<Image Opacity="{x:Bind Opacity, Mode=OneWay}" Source="{x:Bind BmpSource, Mode=OneWay}"> </Image>
3. 修正ItemsSource绑定
你的XAML中绑定的filteredImages在后台代码中未定义,若为笔误,需改为已存在的allImages:
<controls:AdaptiveGridView IsItemClickEnabled="True" ItemsSource="{x:Bind allImages, Mode=OneWay}" SelectionChanged="Items_Select">
4. 移除不必要的Bindings.Update()
由于Opacity已实现INotifyPropertyChanged,属性变更会自动通知UI更新,因此可以删除Items_Select中的冗余代码:
private void Items_Select(object sender, SelectionChangedEventArgs e) { foreach (WorkingImage a in e.AddedItems) { a.Select(); } foreach (WorkingImage r in e.RemovedItems) { r.Deselect(); } // 移除该行:Bindings.Update(); }
额外注意事项
- 遵循C#编码规范,属性名使用PascalCase(首字母大写),避免与UI内置属性混淆。
- 所有需要绑定的属性都应实现
INotifyPropertyChanged,确保UI能响应数据变更。 - 子类构造中无需重复父类已处理的逻辑,比如
base.file的赋值,避免冗余。
内容的提问来源于stack exchange,提问作者Mark L
相关产品推荐
相关产品推荐

