WP7 - 为什么按下 Windows 后退按钮时我的绑定没有触发?
希望对此问题有一个明显的答案,而我凌晨 2 点的大脑还没有看到这一点(这是基于我找不到其他有同样问题的人这一事实)。
当我按下 Windows Phone 7 上的“硬件/内置”后退按钮时,我的任何绑定都不会重新评估。例如,在我的 MainPage 上,我有一个按钮的“IsEnabled”绑定到 ViewModel 中的 bool 属性,该属性检查值是否位于独立存储中。在模拟器中,它以禁用状态启动(显然)。然后,我导航到另一个页面并将所需的值添加到独立存储中。当我按下硬件后退按钮返回原始页面时,绑定不会重新评估,并且我的按钮仍然处于禁用状态。
但是,如果我使用导航方法通过代码返回 MainPage,绑定将被重新评估,一切都很好。
有什么想法吗?
Hopefully there is an obvious answer to this that my brain at 2am is not seeing (I'm basing this on the fact I can't find anyone else with the same problem).
When I press the "hardware/built in" back button on my windows phone 7 none of my bindings are re-evaluating. For example on my MainPage I have a button's "IsEnabled" bound to a bool property in my ViewModel that checks if a value is in isolated storage. In the emulator it starts as disabled (obviously). I then navigate to another page and add the required value to isolated storage. When i press the hardware back button to return to the original page the binding does not get re-evaluated and my button remains disabled.
However if I go back to MainPage via code using the navigate method the binding gets re-evaluated and everything is good.
Any ideas as to why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个问题听起来好像 RaisePropertyChanged 方法不是由 MVVM Light ViewModel 引发的 - 如果您将 ViewModel 上 IsEnabled 属性的 Get{} 访问器直接绑定到isolatedStorage 中的值,那么 ViewModel 将不会知道潜在的价值必然发生了变化。
当您将值写入isolatedStorage时,您可以使用MVVM中的Messenger接口来通知相关ViewModel它应该为您的模型触发RaisePropertyChanged()事件,并且这将在您的视图中重新绑定该属性。
The issue sounds like the RaisePropertyChanged method isn't being raised by your MVVM Light ViewModel - if you're binding Get{} accessor of your IsEnabled property on the viewmodel directly to a value in IsolatedStorage, then the ViewModel isn't going to know that that underlying value has necessarily changed.
When you write the value to IsolatedStorage, you can use the Messenger interface in MVVM to notify the ViewModel-in-question that it should fire the RaisePropertyChanged() event for your model, and that will re-bind that property in your view.
当您使用
NavigationService.Navigate
方法时,您实际上是在执行向前导航,并创建页面的新实例。当您按下硬件后退按钮时,将执行向后导航并重新显示上一页。几乎所有时候,您得到的都是页面原始实例的缓存版本。您可以重新评估页面的
OnNavigedTo
覆盖中的任何绑定,但这会引入相当多的“代码味道”。如上所述,使用Messenger
将使您能够更新关联的视图模型,这将更新页面上的绑定。When you use the
NavigationService.Navigate
method, you are actually performing a forwards navigation and a new instance of your page is created. When you press the hardware back button, a backwards navigation is performed and the previous page is re-displayed. Almost all of the time, what you get is a cached version of the original instance of the page.You could re-evaluate any bindings in the
OnNavigatedTo
override for the page, but this introduces a fair bit of 'code smell'. As mentioned above, using theMessenger
will enable you to update the associated view model, which will update the binding on the page.