WinUI ListView图片绑定运行时不更新问题求助
WinUI ListView图片绑定不随路径更新的解决方案
问题根源
你的SampleObject类未实现INotifyPropertyChanged接口,导致ObjectPath属性值更新时无法通知UI层刷新绑定;同时{x:Bind}默认采用OneTime模式,仅在初始化时绑定一次,后续属性变更不会自动同步到UI。
解决步骤
1. 让SampleObject实现属性变更通知
修改SampleObject类,实现INotifyPropertyChanged接口,并在ObjectPath属性的setter中触发变更事件:
using System.ComponentModel; using System.Runtime.CompilerServices; namespace YourNamespace.ViewModels { public class SampleObject : INotifyPropertyChanged { private string _objectName; private string _objectPath; public string ObjectName { get => _objectName; set => SetProperty(ref _objectName, value); } public string ObjectPath { get => _objectPath; set => SetProperty(ref _objectPath, value); } public event PropertyChangedEventHandler PropertyChanged; private void SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null) { if (Equals(storage, value)) return; storage = value; OnPropertyChanged(propertyName); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
2. 修改XAML绑定为OneWay模式
将Image的Source绑定显式指定为OneWay模式,确保UI能接收属性变更通知:
<Image Grid.Column="1" Source="{x:Bind ObjectPath, Mode=OneWay}" HorizontalAlignment="Left" />
额外注意
确保ViewModel中的List是**ObservableCollectionList,这样集合的增删操作也能自动同步到ListView。如果之前用的是普通List,替换为ObservableCollection即可,无需额外代码。
完成以上修改后,当你更新SampleObject的ObjectPath属性时,图片会自动同步更新,无需手动调用刷新方法。
内容的提问来源于stack exchange,提问作者amatsuraikou
相关产品推荐
相关产品推荐

