1

I have a behavior that I want to track the actions of a control, and I want to read that state off of that behavior from my ViewModel.

Currently I'm doing this:

    <MyControl>
        <i:Interaction.Behaviors>
            <b:MyBehavior />
        </i:Interaction.Behaviors>
    </MyControl>

Is there a way I can bind to the behavior as a property of the ViewModel or some other part of the application rather than instantiating it in XAML? What is the syntax?

Dan Monego
  • 9,637
  • 6
  • 37
  • 72

2 Answers2

2

The behavior is a pure UI concept, the ViewModel is not supposed to know anything about it. However, you could make the behavior update a property of the ViewModel, through a binding. Just declare a dependency property on the behavior and bind it like this:

<MyControl>
    <i:Interaction.Behaviors>
        <b:MyBehavior MyProperty="{Binding MyViewModelProperty, Mode=OneWayToSource}" />
    </i:Interaction.Behaviors>
</MyControl>

(you could also use a TwoWay binding if it makes sense of course)

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • It's a good idea, but behaviors already inherit from Behavior, and can't inherit from DependencyObject. – Dan Monego May 03 '11 at 15:19
  • 2
    @Dan Monego, [Behavior already inherits from DependencyObject](http://msdn.microsoft.com/en-us/library/system.windows.interactivity.behavior%28v=expression.40%29.aspx)... – Thomas Levesque May 03 '11 at 15:20
  • 1
    Levensque - oof. Thanks again - I'll just go debug these "A 'Binding' can only be set on a DependencyProperty of a DependencyObject" errors over here then. – Dan Monego May 03 '11 at 15:27
  • What's the `DataContext` that the `Behavior` gets? Why isn't there a `DataContext` property on it? Is there a way to determine the current `DataContext` or internal binding the `Behavior` is currently set to? – Shimmy Weitzhandler Nov 22 '17 at 05:04
  • 1
    @Shimmy it gets the DataContext of the control – Thomas Levesque Nov 22 '17 at 08:42
0

Most of the logic of Interactivity is internal or private, for example the attached properties Triggers and Behaviors are both private. The Interaction class only provides methods to get behaviors and triggers and has no setter methods. I really doubt that there is much that can be done, at least using the existing classes.

Maybe this question on how to set bahaviors in a style can give you an idea how to realize this.

Community
  • 1
  • 1
H.B.
  • 166,899
  • 29
  • 327
  • 400