Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting "Cannot add instance of type EventTriggerBehavior to collection BehaviorCollection" to make clickable TextBlock

My app had a series of buttons hardcoded to be a navigation menu, but I wanted to upgrade this to something more data-driven.

    <Button Content="MyPage">
        <i:Interaction.Behaviors>
            <core:EventTriggerBehavior EventName="Click">
                <core:NavigateToPageAction TargetPage="Namespace.MyPage"/>
            </core:EventTriggerBehavior>
        </i:Interaction.Behaviors>
    </Button>

But when I tried to put this behavior on a different XAML element (specifically a TextBlock as part of a data template) I got the following error.

An exception of type 'Windows.UI.Xaml.Markup.XamlParseException' occurred in NavMockUp.Windows.exe but was not handled in user code

WinRT information: Cannot add instance of type 'Microsoft.Xaml.Interactions.Core.EventTriggerBehavior' to a collection of type 'Microsoft.Xaml.Interactivity.BehaviorCollection'

    <TextBlock Text="Click for Page">
        <i:Interaction.Behaviors>
            <core:EventTriggerBehavior EventName="Click">
                <core:NavigateToPageAction TargetPage="Namespace.MyPage"/>
            </core:EventTriggerBehavior>
        </i:Interaction.Behaviors>
    </TextBlock>
like image 474
NotAGenie Avatar asked Mar 17 '16 14:03

NotAGenie


1 Answers

Make sure you understand how EventTriggerBehaviors work

The error may be somewhat unhelpful, but this is being caused by the fact that a TextBlock element does not have an event called "Click" to attach to. Jerry Nixon has a good article on behaviors

To fix this simply replace the Click event with the Tapped event, because a TextBlock does have one of those.

    <TextBlock Text="Click for Page">
        <i:Interaction.Behaviors>
            <core:EventTriggerBehavior EventName="Tapped">
                <core:NavigateToPageAction TargetPage="Namespace.MyPage"/>
            </core:EventTriggerBehavior>
        </i:Interaction.Behaviors>
    </TextBlock>
like image 200
NotAGenie Avatar answered Nov 13 '22 06:11

NotAGenie