6

I'm very happy with my small collection of Blend behaviors, actions and triggers - they are easy to use and powerful. But I still can't figure out how to avoid applying them on per element basis. For example, if I have a behavior as such:

<Rectangle>
    <i:Interaction.Behaviors>
        <il:MouseDragElementBehavior/>
    </i:Interaction.Behaviors>
</Rectangle>

and I have a few draggable rectangles in my Window, each of them has to have the above markup to be draggable. What I would like to do is to be able to write something like this:

<Style x:Key="RectangleStyle" TargetType="{x:Type Rectangle}">
    <Setter Property="i:Interaction.Behaviors" 
        Value="il:MouseDragElementBehavior"/>
</Style>

It could be style, template, or some other way to avoid behavior or action markup repetition. The best solution I came up so far is creating a special behavior for the container (when attached, it enumerates children attaching to the children events). Any ideas?

Sergey Aldoukhov
  • 22,316
  • 18
  • 72
  • 99

3 Answers3

3

I ran into the same problem and I posted on my blog on how to create an attached property to work around this shortcoming of the Blend SDK.

  • 1
    this is a broken link. see [this duplicate](http://stackoverflow.com/questions/1647815/how-to-add-a-blend-behavior-in-a-style-setter). – Mike Fuchs May 01 '13 at 14:57
1

I haven't tried it, but what I would probably do is create an attached property that can hold a collection of Behaviors. In the property changed handler of that property, I would enumerate the collection and add each of the behaviours to the real Interation.Behaviors property. It's a bit messy, but it ought to work.

Update

This approach won't work without a good deal more work: the problem is that Behaviors and Triggers can only be attached to one object at a time. This is probably why the limitation on applying them using a style exists in the first place. To get this to work you would need to create some kind of Trigger or Behavior factory.

Samuel Jack
  • 32,712
  • 16
  • 118
  • 155
0

You could create your own class that inherits from Rectangle and apply the behavior there.

Charlie
  • 15,069
  • 3
  • 64
  • 70
  • 1
    In that case I would not even need behavior - I could wire up events directly. Naw, I'd rather leave our designer something to do... – Sergey Aldoukhov Aug 10 '09 at 17:41