View间ViewModel数据共享问题:ViewB无法自动更新求助
问题原因及解决方案
你的ViewB无法自动更新,核心是两个关键问题没处理到位:
1. UserController的CurrentUser未触发属性变更通知
虽然你的UserController继承了BindableBase,但当前的CurrentUser是自动实现属性,即便配置了Fody,也可能因写法问题没生成PropertyChanged通知逻辑。正确做法是用BindableBase提供的SetProperty方法显式处理,确保属性变更时能触发通知:
public class UserController : BindableBase { private static UserController instance; private User _currentUser; public User CurrentUser { get => _currentUser; set => SetProperty(ref _currentUser, value); } public static UserController Instance { get { if (instance == null) instance = new UserController(); return instance; } } private UserController() { } }
2. ViewModelB的CurrentUser无法感知UserController的属性变化
你在ViewModelB中用表达式体定义的CurrentUser:
public User CurrentUser => UserController.Instance.CurrentUser;
这是只读属性,只会在ViewModel初始化时获取一次值,后续UserController的CurrentUser变更时,ViewModelB不会主动通知UI更新。有两种解决思路:
方案一:直接绑定到UserController实例
在ViewModelB中暴露UserController单例,省去中间包装层:
public UserController UserController => UserController.Instance;
修改ViewB的绑定路径:
<TextBox Text="{Binding UserController.CurrentUser.UserName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
UI会直接监听UserController的属性变化,无需ViewModel额外处理。
方案二:订阅UserController的变更事件并触发自身通知
如果必须保留ViewModelB的CurrentUser属性,可以在ViewModel中订阅UserController的PropertyChanged事件,当CurrentUser变更时主动通知UI:
public class UserInfoPageViewModel : BindableBase, IDisposable { public User CurrentUser => UserController.Instance.CurrentUser; public UserInfoPageViewModel() { UserController.Instance.PropertyChanged += UserController_PropertyChanged; } private void UserController_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(UserController.CurrentUser)) { RaisePropertyChanged(nameof(CurrentUser)); } } public void Dispose() { UserController.Instance.PropertyChanged -= UserController_PropertyChanged; } }
额外注意点
如果需要修改UserName时UI也能实时更新,你的User类也必须实现INotifyPropertyChanged接口(同样可以用BindableBase或Fody简化实现)。
内容的提问来源于stack exchange,提问作者Kevin Plaul
相关产品推荐
相关产品推荐

