从后台线程或在计时器刻度上更新与viewmodel属性绑定的xaml控件

时间:2019-05-13 05:13:06

标签: c++ windows-runtime windows-10-universal uwp-xaml c++-cx

我有实现INotifyPropertyChanged的视图模型。

public ref class MyViewModel sealed: Windows::UI::Xaml::Data::INotifyPropertyChanged
{
  public:
    // Inherited via INotifyPropertyChanged
    virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged;

    property float Temperature
    {
        float get() { return m_temperature; }
        void set(float temperature) { SetProperty(m_temperature, temperature, "Temperature"); }
    }

    protected:
        void OnPropertyChanged(Platform::String ^ propertyName);

    private:
        float m_temperature = 0.0f;

    protected private:
        template<typename T>
        bool SetProperty(T& storage, T value, Platform::String^ propertyName)
        {
            if (storage == value) return false;
            storage = value;
            OnPropertyChanged(propertyName);
            return true;
        }
}

在MainPage计时器中,我尝试更新相关控件,如下所示:

void MainPage::OnDeviceControllerPollingTick(Object^ sender, Object^ e)
{
Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
    CoreDispatcherPriority::Normal,
    ref new Windows::UI::Core::DispatchedHandler([this]()
{
    const float temperature = 10.0f;
    MyViewModelObject->Temperature = temperature;
}));
}

从计时器滴答声或后台线程更新绑定控件的正确方法是正确的方法吗?

0 个答案:

没有答案