0

I have a WPF app, with a tree view. There's an item template that is hierarchical.

I want to bind an image source to the data class I'm using as TreeViewItem i.e. to RestoreItemVM. What do I need to write in the path??? Everything I tried so far threw an error in my converter saying it's cannot cast it to RestoreItemVM...

<TreeView.ItemTemplate>
    <HierarchicalDataTemplate ItemsSource="{Binding Children}" DataType="restoreTab:RestoreItemVM">
        <DockPanel VerticalAlignment="Center" HorizontalAlignment="Left" LastChildFill="False">
            <CheckBox Focusable="False" VerticalAlignment="Center" IsChecked="{Binding IsChecked}" PreviewMouseRightButtonDown="TreeViewItem_OnPreviewMouseRightButtonDown"/>
            <Image Width="20" Margin="3" 
                   Source="{Binding RelativeSource={RelativeSource 
                            FindAncestor, AncestorType={x:Type TreeViewItem}, 
                            AncestorLevel=2}, Converter={x:Static local:RestoreItemToImageConverter.Instance}, 
                            Path= ????? }"  
                   PreviewMouseRightButtonDown = "TreeViewItem_OnPreviewMouseRightButtonDown"/>
       </DockPanel>
    </HierarchicalDataTemplate>
</TreeView.ItemTemplate>
Maverick Meerkat
  • 5,737
  • 3
  • 47
  • 66

1 Answers1

1

You need to specify the path to the data context:

Source="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type TreeViewItem}}, Converter={x:Static local:RestoreItemToImageConverter.Instance}, 
         Path=DataContext}"

But actually, it's more simple, as RestoreItemVM is already the DataContext of Image as well, you don't need to find it's ancestor. Instead try this:

<Image ... Source="{Binding Path=., Converter={x:Static local:RestoreItemToImageConverter.Instance}}" />

Path=. binds to the DataContext itself:

Special symbols in WPF binding - what does "{Binding Path=.}" mean?

And the DataContext of the DockPanel in the HierarchicalDataTemplate is the current RestoreItemVM object in the ItemsSource.

Maverick Meerkat
  • 5,737
  • 3
  • 47
  • 66
mm8
  • 163,881
  • 10
  • 57
  • 88
  • Hmm.. this actually works. Can you add some more explanations before I accept it - like, what does Path=. means ? – Maverick Meerkat Sep 14 '17 at 15:26
  • Path=. means bind to the DataContext itself: https://stackoverflow.com/questions/1066262/special-symbols-in-wpf-binding-what-does-binding-path-mean – mm8 Sep 14 '17 at 15:27
  • I added some more information. Please approve, and I'll accept – Maverick Meerkat Sep 14 '17 at 15:32
  • 1
    To add some precision, `Path=.` (or just omitting Path, since `.` is the default) means to bind directly to the current source object of the Binding. Depending on how the source was actually set, this is either the current DataContent, or the object referred to by the Binding's Source, RelativeSource or ElementName properties. – Clemens Sep 14 '17 at 15:33