首页 > 解决方案 > 我们什么时候应该实现 INotifyPropertyChanged

问题描述

我的主页包含视图模型属性,并且主页 xaml 元素通过 x:bind 与视图模型属性绑定。我需要为主页实现 INotifyPropertyChanged 吗?

如果 INotifyPropertyChanged 未在主页中实现,则不存在构建问题。但更新绑定属性有时会引发运行时异常。

但是当我为主页实现 INotifyPropertyChanged 时,一切正常。

property VM::TheViewModel^ ViewModel
{
   VM::TheViewModel^ get()
   {
       return VM::AppData::ViewModel;
   }
}

AppData 类提供静态视图模型

ref class AppData
    {
    public:
        static property VM::TheViewModel^ ViewModel
        {
            VM::TheViewModel^ get()
            {
                static VM::TheViewModel^ vm= ref new vm::TheViewModel();
                return vm;
            }
        }
    }

xaml 数据绑定:

ItemsSource="{x:Bind ViewModel.MyProperty}"

我不确定我为什么要实施

INotifyPropertyChanged

用于主页。当我在视图模型类中有属性时?

从后台线程我停止我的计时器。导航到初始页面,然后在某些条件下返回主页。通过启动计时器并运行后台线程切换回主页时,会发生运行时异常。这不是常规情况。有时会发生有时不会。但它发生了。

OnSomeModelChange()
{
...
    if (notifyId == SessionPropertyNotifyType::Session)
        {
            StopTimers();
            AppData::ViewModelInfo->ClearErrors();
            auto rootFrame = dynamic_cast<Frame^>(Window::Current->Content);
            rootFrame->Navigate(TypeName(InitPage::typeid), nullptr, ref new Animation::SuppressNavigationTransitionInfo);
            Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
                Windows::UI::Core::CoreDispatcherPriority::Low,
                ref new Windows::UI::Core::DispatchedHandler([this]() { InitSessionAsync(); }, CallbackContext::Any)
            );
        }
...
}

调用堆栈: 在此处输入图像描述

异常:抛出异常:读取访问冲突。

this->__this->**** was 0xDDDDDDDD.

标签: winrt-xamluwp-xamlc++-cx

解决方案


推荐阅读