Search code examples
c#wpftreeviewitem

TreeViewItem to notify ViewModel when it is hovered


I am currently using the code from this blogpost in order to have my TreeView highlight those items, which are currently hovered by the mouse. This is working as intended, however now I want the TreeViewItems to notify their attached ViewModels when they are hovered / not hovered.

However I'm at a loss on how I can achieve this. The corresponding XAML code looks like the following:

<Style TargetType="{x:Type TreeViewItem}">
    <Style.Triggers>
        <Trigger Property="Controls:TreeViewHelper.IsMouseDirectlyOverItem" Value="True">
            <Setter Property="Background" Value="Green" />
        </Trigger>
    </Stile.Triggers>
</Style>

How can I bind the property from my ViewModel, named TreeNodeModel.IsHovered to the TreeViewItem (or probably the attached dependency property IsMouseDirectlyOverItem) so that I can react on those changes from within my code?

All the examples I found via google only explained how the set the background color. Thanks in advance for your time on the probably trivial answer.


Solution

  • In your Style, try adding a Setter which binds IsMouseDirectlyOverItem to IsHovered, and use the OneWayToSource binding mode to push the value the right way:

    <Style TargetType="{x:Type TreeViewItem}">
        <Setter Property="Controls:TreeViewHelper.IsMouseDirectlyOverItem"
                Value="{Binding Path=IsHovered, Mode=OneWayToSource}" />
    
        <Style.Triggers>
            ...
    </Style>
    

    EDIT: As IsMouseDirectlyOver is read-only, and read-only DPs can't be the target of any bindings, Fredrik Hedblad's PushBinding may be a possible workaround: OneWayToSource Binding for ReadOnly Dependency Property

    <Style TargetType="{x:Type TreeViewItem}">
        <Setter Property="pb:PushBindingManager.StylePushBindings">
            <Setter.Value>
                <pb:PushBindingCollection>
                    <pb:PushBinding TargetDependencyProperty="Controls:TreeViewHelper.IsMouseDirectlyOverItem" 
                                    Path="IsHovered" />
                </pb:PushBindingCollection>
            </Setter.Value>
        </Setter>
    
        <Style.Triggers>
            ...
    </Style>