Search code examples
c++windowsuwpc++17c++-winrt

c++ winrt uwp how to get value out of dependency property


Given a dependency property in a Custom attached property defined in it's class as

   private:
            static Windows::UI::Xaml::DependencyProperty m_IsOpenProperty;

I have tried,


bool FlyoutCloser::GetIsOpen(Windows::UI::Xaml::DependencyObject const& target)
    {
        return target.GetValue(m_IsOpenProperty).as<bool>();

    }

however here the compiler is telling me C++ no suitable conversion function from to exists converting from winrt::impl::com_ref<bool> to "bool" exists. How can I get a boolean value out of it.


Solution

  • target.GetValue() will return an IInspectable type, you need to use winrt::unbox_value function to unbox an IInspectable back into a scalar value instead of using as method. And about boxing and unboxing, you can refer to this document.

    bool FlyoutCloser::GetIsOpen(Windows::UI::Xaml::DependencyObject const& target)
    {
        return winrt::unbox_value<bool>(target.GetValue(m_IsOpenProperty));
    }
    
    void FlyoutCloser::SetIsOpen(Windows::UI::Xaml::DependencyObject const& target, bool value)
    {
        target.SetValue(m_IsOpenProperty, winrt::box_value(value));
    }