Behaviour<T> + VisualStateManager - Templates not applied
Posted: 23 Feb 2021, 02:36
Hi guys, I'm trying to use a custom Behaviour<T> with the VisualStateManager:
This fails to run as the template is not yet applied. There is not a nice way from what I can see to hook in to add this behaviour. Normally in Custom Controls I'd derive from OnApplyTemplate virtual and add this behaviour here, is there an alternative for behaviours?
My workaround is to force ApplyTemplate:
But this doesn't feel clean. Any ideas? Cheers!
-Steven
Code: Select all
/*virtual*/ void CustomButtonBehaviour::OnAttached() /*override*/
{
Button *pBaseButton = GetAssociatedObject();
pBaseButton->DependencyPropertyChanged() += MakeDelegate(this, &OnPropertyChanged);
}
void CustomButtonBehaviour::OnPropertyChanged(BaseComponent*, const DependencyPropertyChangedEventArgs &rArgs)
{
if (rArgs.prop == ContentControl::ContentProperty)
{
Button *pButton = GetAssociatedObject();
if (nullptr != pButton->GetContent())
{
VisualStateManager::GoToState(pButton, NSS(CustomVisualState), false);
}
}
}
My workaround is to force ApplyTemplate:
Code: Select all
void CustomButtonBehaviour::OnPropertyChanged(BaseComponent*, const DependencyPropertyChangedEventArgs &rArgs)
{
if (rArgs.prop == ContentControl::ContentProperty)
{
Button *pButton = GetAssociatedObject();
if (nullptr != pButton->GetContent())
{
pButton->ApplyTemplate(); // Force apply template so visual child is set
VisualStateManager::GoToState(pButton, NSS(CustomVisualState), false);
}
}
}
-Steven