【发布时间】:2017-07-25 02:18:24
【问题描述】:
x:Bind 默认为 OneTime,当 Page 的 Loading 事件触发生成代码的 Initialize 函数时,用数据更新目标 UI。
我有一个带有 ViewModel 属性的页面。此 ViewModel 类为其属性实现 INPC。 viewModel 的数据是异步加载的,只有在页面加载之后。因此,在 Page 初始化以及随后生成的代码初始化时,使用 x:Bind 的 UI 目标将具有空数据。
因为它是 OneTime,它不应该改变,除非我手动调用 Update(我没有)。
那么为什么我的 x:Bind UI 可以工作?
以下是一些简化的代码sn-ps。
<Page x:Name="MyPage" x:Class="MyProject.Pages.MyPage">
<Button Command="{x:Bind ViewModel.GoToAnotherPageCommand}">
public sealed partial class MyPage : Page
{
public MyPageViewModel ViewModel { get; set; }
public MyPage()
{
this.InitializeComponent();
}
// called by an event bound to a Frame's Navigated, which all pages use
public void OnNavigatedTo()
{
this.ViewModel = new MyPageViewModel();
}
}
public class MyPageViewModel : INotifyPropertyChanged, INotifyPropertyChanging
{
// GoToAnotherPageCommand is an INPC property and its set in the constructor
【问题讨论】:
-
总结贾斯汀的回答,页面的加载事件发生在框架的导航事件之前,因此在导航上完成 ViewModel 初始化的页面调用 .Navigate 将在 OneTime x:Bind 时提供数据获取数据的值。一个例外是数据的异步初始化,不能保证在引发 Loading 事件时准备好。