gpt4 book ai didi

c# - XAML x :bind oneTime on initially null property still works. 为什么?

转载 作者:太空宇宙 更新时间:2023-11-03 22:56:08 26 4
gpt4 key购买 nike

x:Bind 默认为 OneTime,当页面的 Loading 事件触发生成代码的 Initialize 函数时,它会使用数据更新目标 UI。

我有一个带有 ViewModel 属性的页面。此 ViewModel 类为其属性实现 INPC。 viewModel 的数据是异步加载的,仅在页面加载后加载。因此在页面初始化以及随后生成的代码初始化时,使用 x:Bind 的 UI 目标将具有空数据。

因为它是 OneTime,所以它不应该改变,除非我手动调用 Update(我没有)。

那么为什么我的 x:Bind UI 可以工作?

以下是一些简化的代码片段。

<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

最佳答案

您的命令运行良好的原因是因为 OnNavigatedTo将在命令实例化之前 被调用。这意味着当代码尝试设置命令时,ViewModel已经被实例化,不再是null .

为了证明我的观点,首先打开以下路径下的文件(可以是 ARM 或 *x64,具体取决于您运行的平台)-

obj/x86/Debug/MyPage.g.cs

这基本上是连接所有 x:Bind 的代码生成文件你的页面的东西。

现在在设置命令的地方放置一个断点。就我而言,这是一个名为 Set_Windows_UI_Xaml_Controls_Primitives_ButtonBase_Command 的方法.然后在 OnNavigatedTo 处放置另一个断点 .

现在运行应用程序,您会看到 OnNavigatedTo方法首先被调用。

如果您的页面的 NavigationCacheMode设置为 Disabled ,这种行为使得OnNavigatedTo实例化的理想场所x:Bind绑定(bind),因此页面仅在用户实际导航到页面时使用内存来创建这些新对象,而不是在页面构造函数中执行所有操作。

不要在 Loaded 中执行此操作Page 事件尽管。因为它将在命令实例化之后 被调用。您可以尝试以下代码来实例化 ViewModel ,结果非常不同(您的命令将不起作用)。

public MyPage()
{
InitializeComponent();

Loaded += (s, e) => ViewModel = new MyPageViewModel();
}

关于c# - XAML x :bind oneTime on initially null property still works. 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45292829/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com