3
votes

I'm creating Behavior with attached properties. Behavior should attach to Grid:

public class InteractionsBehavior : Behavior<Grid>
{
    public static readonly DependencyProperty ContainerProperty =
        DependencyProperty.RegisterAttached("Container", typeof(Grid), typeof(Grid), new PropertyMetadata(null));

    public static readonly DependencyProperty InteractionsProviderProperty =
        DependencyProperty.RegisterAttached("InteractionsProvider", typeof(IInteractionsProvider), typeof(Grid), new PropertyMetadata(null, OnInteractionsProviderPropertyChanged));

    public Grid Container
    {
        get { return GetValue(ContainerProperty) as Grid; }
        set { this.SetValue(ContainerProperty, value); }
    }

    public IInteractionsProvider InteractionsProvider
    {
        get { return GetValue(InteractionsProviderProperty) as IInteractionsProvider; }
        set { this.SetValue(InteractionsProviderProperty, value); }
    }

Now when I'm writing XAML like this I get error:

<Grid Background="White" x:Name="LayoutRoot" 
          Behaviors:InteractionsBehavior.InteractionsProvider="{Binding InteractionsProvider}">

Error 4 The property 'InteractionsProvider' does not exist on the type 'Grid' in the XML namespace 'clr-namespace:Infrastructure.Behaviors;assembly=Infrastructure.SL'. C:\MainPage.xaml 11 11 Controls.SL.Test

Error 1 The attachable property 'InteractionsProvider' was not found in type 'InteractionsBehavior'. C:\MainPage.xaml 11 11 Controls.SL.Test

2

2 Answers

3
votes

You specified that it only should be available to be attached ("owned") by an InteractionsBehavior. If you want to be able to assign this to a grid, change the RegisterAttached line to:

public static readonly DependencyProperty InteractionsProviderProperty =
        DependencyProperty.RegisterAttached("InteractionsProvider", typeof(IInteractionsProvider), typeof(Grid), new PropertyMetadata(null, OnInteractionsProviderPropertyChanged));

(Or use some base class in Grid's class hierarchy...)

1
votes

The problem is in the declaration of your attached property. Attached properties have 4 parts: the name, the type, the owner type, and the property metadata. You're specifying that the InteractionsProvider property is owned (and thus supplied) by the type Grid. That's not actually the case. Change the owner type (third parameter) to typeof(InteractionsBehavior) (the class in which you've declared the attached property), switch to static get/set methods instead of a property (because you're using an attached property, not a dependency property), and it should all work as you expect.