0

Using this link I'm able to set a Property on the a TreeViewItem when the mouse is over it (in this case the background color):

<controls:LinkedTreeView x:Name="ltv" ItemsSource="{Binding Items}" LinkedHighlightedItem="{Binding HighlightedItem, Mode=TwoWay}">
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}">
            <Style.Triggers>                
                <Trigger Property="ap:TreeViewHelper.IsMouseDirectlyOverItem" Value="True">
                    <Setter Property="Background" Value="Red"/>
                </Trigger>
            </Style.Triggers>
            <Setter Property="Background" Value="Transparent"/>
        </Style>
    </TreeView.ItemContainerStyle>
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate DataType="{x:Type model:TreeItem}" ItemsSource="{Binding Children}">
            <TextBlock Text="{Binding Name}"/>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</controls:LinkedTreeView>

Now I want to know that the mouse is over a TreeViewItem in my ViewModel (and get its DataContext). I've tried to make this work by making a DependencyProperty on my custom LinkedTreeViewcontrol called LinkedHighlightedItem and bind this to a Property called HighlightedItem on my ViewModel. Now I want to set this to the current DataContext of the TreeViewItem where the mouse is over, only I cannot acces the LinkedTreeView control from my TreeViewItem Style.Triggers. It says the name "ltv" is not recognized. I've used an extra trigger here to set the value:

<Trigger Property="ap:TreeViewHelper.IsMouseDirectlyOverItem" Value="True">
    <Setter Property="Background" Value="Red"/>
    <Setter TargetName="ltv" Property="LinkedHighlightedItem" Value="{Binding Path=DataContext, RelativeSource={RelativeSource Mode=Self}}"/>
</Trigger>

How can I fix this? Or is there some other way to know from the ViewModel which item the mouse is over?

MrEighteen
  • 356
  • 4
  • 15
  • You could define `LinkedHighlightedItem` as an [attached property](https://docs.microsoft.com/en-us/dotnet/desktop/wpf/advanced/how-to-register-an-attached-property?WT.mc_id=WD-MVP-5001077), set it using a trigger and bind it to a source property of your data object. – mm8 Oct 26 '20 at 15:14
  • Thnx for your input! I not sure I fully understand though. So I make an attached property to the TreeViewItem, for instance `LinkedHighlightedItem` and set it using the `Setter` just like I set the background in my example. Now how do I get that information to the ViewModel of the `TreeView` (and not the `TreeViewItem`)? – MrEighteen Oct 27 '20 at 09:41
  • You also bind the dependency property to a source property. – mm8 Oct 27 '20 at 13:34

0 Answers0