如何在C++/CX类中注册float值类型的DependencyProperty
How to Register a
float DependencyProperty in C++/CX I’ve been in your shoes—getting value-type DependencyProperties working in C++/CX can feel counterintuitive after dealing with reference types like Brush. The core issue with your attempts is that native C++ value types (like float) need to be boxed to work with WinRT’s DependencyProperty system, which expects a WinRT-compatible type reference.
The Correct Type Parameter
Instead of typeid(float) or your other attempts, use Platform::Box<float>::typeid as the second argument to DependencyProperty::Register. This gives you the WinRT type information for the boxed float value, which is exactly what the method requires.
Full Example Code
Header File (MyCustomClass.h)
#pragma once #include "Windows.UI.Xaml.h" namespace YourNamespace { public ref class MyCustomClass sealed : Windows::UI::Xaml::DependencyObject { public: static property Windows::UI::Xaml::DependencyProperty^ MyFloatProperty { Windows::UI::Xaml::DependencyProperty^ get(); }; property float MyFloat { float get(); void set(float value); }; private: static Windows::UI::Xaml::DependencyProperty^ _myFloatProperty; static void OnMyFloatChanged(Windows::UI::Xaml::DependencyObject^ d, Windows::UI::Xaml::DependencyPropertyChangedEventArgs^ e); }; }
Implementation File (MyCustomClass.cpp)
#include "pch.h" #include "MyCustomClass.h" using namespace Windows::UI::Xaml; using namespace Platform; namespace YourNamespace { DependencyProperty^ MyCustomClass::MyFloatProperty::get() { return _myFloatProperty; } float MyCustomClass::MyFloat::get() { // Unbox the stored value from the DependencyProperty return safe_cast<IBox<float>^>(GetValue(MyFloatProperty))->Value; } void MyCustomClass::MyFloat::set(float value) { // Box the float when passing it to SetValue SetValue(MyFloatProperty, Box<float>::Create(value)); } DependencyProperty^ MyCustomClass::_myFloatProperty = DependencyProperty::Register( "MyFloat", Box<float>::typeid, MyCustomClass::typeid, ref new PropertyMetadata( // Default value is a boxed float (0.0f in this case) Box<float>::Create(0.0f), ref new PropertyChangedCallback(&MyCustomClass::OnMyFloatChanged) ) ); void MyCustomClass::OnMyFloatChanged(DependencyObject^ d, DependencyPropertyChangedEventArgs^ e) { MyCustomClass^ instance = safe_cast<MyCustomClass^>(d); float oldValue = safe_cast<IBox<float>^>(e->OldValue)->Value; float newValue = safe_cast<IBox<float>^>(e->NewValue)->Value; // Add your property change logic here } }
Key Notes:
- When retrieving the property value, you must unbox it with
safe_cast<IBox<float>^>and access theValueproperty to get the native float. - When setting the property or defining the default value in
PropertyMetadata, you have to box the float usingBox<float>::Create(value). - This pattern works for all native value types—just replace
floatwithint,double,bool, etc., and use the correspondingPlatform::Box<T>::typeid.
内容的提问来源于stack exchange,提问作者ackh
相关产品推荐
相关产品推荐

