Search code examples
xamlwinrt-xamlwindows-8.1windows-phone-8.1expression-blend

How do I implement a custom behavior in XAML


How do I implement a custom behavior in XAML specifically for Windows Phone 8.1?

I am using VS2013 and Blend 2013.

Code:

public class SelectionBehavior : IBehavior
{
    public DependencyObject AssociatedObject
    {
        get { throw new NotImplementedException(); }
    }

    public void Attach(DependencyObject associatedObject)
    {
        throw new NotImplementedException();
    }

    public void Detach()
    {
        throw new NotImplementedException();
    }
}

XAML:

xmlns:Interactivity="using:Microsoft.Xaml.Interactivity" xmlns:Core="using:Microsoft.Xaml.Interactions.Core" xmlns:Media="using:Microsoft.Xaml.Interactions.Media" x:Name="page"

<Interactivity:Interaction.Behaviors>
    <behaviors:SelectionBehavior />
</Interactivity:Interaction.Behaviors>

When I attempt to build the solution, I receive the following errors:

The specified value cannot be assigned to the collection. The following type was expected: "DependencyObject".

Cannot add 'SelectionBehavior' into the collection property 'Behaviors', type must be 'DependencyObject'

A value of type 'SelectionBehavior' cannot be added to a collection or dictionary of type 'BehaviorCollection'.


Solution

  • Your behavior should inherit from DependencyObject, try this -

    public class SelectionBehavior : DependencyObject, IBehavior