I have a treeview which is created from ItemsSource of SecondViewModel instances, different from my Window DataContext.
I want to send the ViewModel that belongs to the TreeViewItem via a `CommandParameter.
The window data context is: MyViewModel.
The treeviewitems data context is: SecondViewModel
I want to pass the SecondViewModel and not MyViewModel.
Therefore,
CommandParameter ="{Binding}"
Won’t work (as it will send MyViewModel)
Edit: Some Code:
<TreeView Name="treeView" ItemContainerStyle="{StaticResource TreeViewItemStyle}" Grid.Row="1" Grid.Column="1">
<TreeViewItem Header="{Binding ProjectName}">
<TreeViewItem commandBehaviors:MouseDoubleClick.Command="{Binding SelectOtherTab}"
commandBehaviors:MouseDoubleClick.CommandParameter="{Binding}" //this returns the data context of the window, I want to return the Item Source
ContextMenu="{StaticResource AddClassMenu}" ItemTemplate="{DynamicResource ClassDataTemplate}" ItemsSource="{Binding ClassCollection}">
How can I send the SecondViewModel?
EDIT:
I want to enable deleting the current item, but the command never gets called for some reason.
Here’s the code:
<TreeViewItem x:Name="treeViewItem"
ContextMenu="{StaticResource AddClassMenu}" ItemTemplate="{DynamicResource ClassDataTemplate}" ItemsSource="{Binding ClassCollection}">
<TreeViewItem.ItemContainerStyle>
<Style TargetType="TreeViewItem">
HERE->> <Setter Property="ContextMenu" Value="{StaticResource RemoveClassMenu}"/>
<Setter Property="commandBehaviors:MouseDoubleClick.Command"
Value="{Binding ElementName=treeViewItem, Path=DataContext.SelectOtherTab}" />
<Setter Property="commandBehaviors:MouseDoubleClick.CommandParameter"
Value="{Binding }" />
</Style>
</TreeViewItem>
My Context Menu:
<ContextMenu x:Key="RemoveClassMenu">
<MenuItem Header="Delete" Command="{Binding ElementName=treeViewItem, Path=DataContext.RemoveClass}" CommandParameter="{Binding}"/>
</ContextMenu>
As mentions before, the command just never gets called. What is the problem with my code?
I think what you’re looking to do is set your
DoubleClickcommands on your childTreeViewItems, not your parentTreeViewItemwhich sets theItemsSourceRight now your XAML is saying to build a parent
TreeViewItem, and under that build a bunch of childTreeViewItemsfor each item inClassCollection. When you double click on the parentTreeViewItemthen run theSelectOtherTabcommand, however there’s nothing to specify which childTreeViewItemgot clicked.Here’s a simplified view of the XAML you have now.
Instead you want to attach the
CommandandCommandParameterproperties to each childTreeViewItem, like this:Which will make your simplified XAML look something like this:
I’m still a bit confused by why you have a parent
TreeViewItemand are building childTreeViewItemsusing it’sItemsSource, however if that’s not necessary you can simplify your VisualTree by eliminating the parentTreeViewItemlike this:Which will make your TreeView look like this: