I’d like to create an attached property in my C++/Cx WinRT project. When I do so, the XAML compiler complains that I’m using an unknown property.
I’m declaring my attached property in a cpp file as such:
/*--------------------------------------------------------------------
Forward Declarations
--------------------------------------------------------------------*/
namespace
{
void
StateChanged(
DependencyObject^ target,
DependencyPropertyChangedEventArgs^ args);
}
/*--------------------------------------------------------------------
DependancyProperty setup for the view model
--------------------------------------------------------------------*/
namespace
{
DependencyProperty^ _stateProperty =
DependencyProperty::RegisterAttached(
"State",
TypeName(Platform::String::typeid),
TypeName(VisualStateManagerBindingHelper::typeid),
ref new PropertyMetadata(nullptr, ref new PropertyChangedCallback(&StateChanged)));
}
namespace
{
void
StateChanged(
DependencyObject^ target,
DependencyPropertyChangedEventArgs^ args)
{
if (args->NewValue != nullptr)
{
VisualStateManager::GoToState(safe_cast<Control^>(target), safe_cast<String^>(args->NewValue), true);
}
}
}
In my XAML file, I’m attempting to use the attached property as such:
<UserControl
xmlns:local="using:MyCustomNamespace"
...
<Grid Grid.Column="1" local:VisualStateManagerBindingHelper.State="{Binding Path=SomeViewModelProperty, Mode=TwoWay}">
...
When I compile, I’m faced with this error:
XamlCompiler error WMC0010: Unknown attachable member ‘VisualStateManagerBindingHelper.State’ on element ‘Grid’
It appears to me as if the XAML compiler is supposed to get a hint somewhere that this attached property is allowed, but I don’t know how to give it that hint. This article on the same subject suggests that the DependancyProperty should be public. I’m not entirely sure how to do that in C++.
My ultimate goal is to bind a visual state group’s state to some view model property. The method to do this is outlined in the accepted answer in this question. Unfortunately, the code provided there is C# and I can’t seem to translate it over to C++ properly.
Finally, I noticed the SuspensionManager that comes with Visual Studio’s new project templates defines an attached property almost exactly like I do, but they don’t show any examples of it in use. This makes me feel like I’m on track, but missing some small piece of the puzzle.
I found a site that answered my question! As I suspected, you need to have your class defined in a very specific way for the XAML preprocessor to know about your attached property. All of the requirements along with a code sample are available here.