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>
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
.