I have crated a Blend behavior for Button. How can I set that to all of my Buttons in the app.
<Button ...>
<i:Interaction.Behaviors>
<local:MyBehavior />
</i:Interaction.Behaviors>
</Button>
However, when I try:
<Style>
<Setter Property="i:Interaction.Behaviors">
<Setter.Value>
<local:MyBehavior />
</Setter.Value>
</Setter>
</Style>
I get the error
The property "Behaviors" does not have an accessible setter.
Declare individual behavior/trigger as Resources :
Insert them in the collection :
Behavior code expects a Visual, so we can add it only on a visual. So the only option I could see is to add to one of the element inside the ControlTemplate so as to get the behavior added to the Style and affect on all the instance of a particular control.
Summing answers and this great article Blend Behaviors in Styles, I came to this generic short and convinient solution:
I made generic class, which could be inherited by any behavior.
So you could simply reuse it with lot of components like this:
And in XAML enough to declare:
So basicly the AttachableForStyleBehavior class made xaml things, registering the instance of behavior for each component in style. For more details, please see the link.
I like the approach shown by the answers by Roman Dvoskin and Jonathan Allen in this thread. When I was first learning that technique though, I benefited from this blog post which provides more explanation about the technique. And to see everything in context, here is the entire source code for the class that the author talks about in his blog post.
I couldn't find the original article but I was able to recreate the effect.
The article Introduction to Attached Behaviors in WPF implements an attached behavior using Style only, and may also be related or helpful.
The technique in the "Introduction to Attached Behaviors" article avoids the Interactivity tags altogether, using on Style. I don't know if this is just because it is a more dated technique, or, if that still confers some benefits where one should prefer it in some scenarios.