Search code examples
c#wpfmvvmlistviewitem

Adding commands for Contextmenu inside ListViewItem Style


I am searching for a solution for the ContextMenu's commands defined under ListViewItem style. Binding was successful when I defined and bind the commands inside ContextMenu within ListView.

I used viewModel class file to define the commands ex: ExecuteClone, CanExecuteClone which i am trying to bind it with ContextMenu menu items using Command Binding.

 <ListView.ContextMenu>
            <ContextMenu >
                <MenuItem Header="New" Command="{Binding AddCommand}" />
            </ContextMenu>
 </ListView.ContextMenu>

But when i change the ContextMenu from ListView to ListViewItem, it doesn't hit the ViewModel command.

<ListView.ItemContainerStyle>
            <Style TargetType="{x:Type ListViewItem}">
                    <Setter Property="ContextMenu">
                    <Setter.Value>
                        <ContextMenu>
                            <MenuItem Header="New" Command="{Binding AddCommand}"/>
                            <MenuItem Header="Clone" Command="{Binding CloneCommand}"/>
                        </ContextMenu>
                    </Setter.Value>
                </Setter>
            </Style>
        </ListView.ItemContainerStyle>

It needs to hit the ViewModel AddCommand, CloneCommand which are DelegateCommand actions defined under ViewModel class.


Solution

  • I found the answer with some trials, anyways thanks for the help.

    <ListView.ItemContainerStyle>
                <Style TargetType="{x:Type ListViewItem}">
                    <Setter Property="Tag" Value="{Binding RelativeSource={RelativeSource AncestorType=ListView}, Path=DataContext}"/>
                    <Setter Property="ContextMenu">
                        <Setter.Value>
                            <ContextMenu DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
                                <MenuItem Header="New" Command="{Binding AddCommand}"/>
                                <MenuItem Header="Clone" Command="{Binding CloneCommand}"/>
                            </ContextMenu>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ListView.ItemContainerStyle>