pass contextmenu parent as CommandParameter

戏子无情 提交于 2019-12-18 09:45:56

问题


i have a HierarchicalDataTemplate for a TreeViewItem, in the template i have a contextmenu and i want to pass as CommandParameter the ContextMenu parent - i.e the TreeViewItem owner that was right clicked at the moment, is there a way to do that? here is my template:

    <HierarchicalDataTemplate 
    x:Key="ServerTemplate"
    DataType="{x:Type models:Server}" 
    ItemsSource="{Binding Channels}"
    ItemTemplate="{StaticResource ChannelTemplate}">
    <StackPanel
        Tag="{Binding DataContext,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}"
        Orientation="Horizontal">
        <StackPanel.ContextMenu>
            <ContextMenu
                FontSize="14"
                FontFamily="Arial">
                <MenuItem 
                    Header="{x:Static p:Resources.ServerOperations_CommunicationSettings}"
                    Command="{Binding PlacementTarget.Tag.ServerCommunicationSettingCommand, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ContextMenu}}}"
                    CommandParameter="{Binding Path=Parent, RelativeSource={RelativeSource Mode=Self}}">
                </MenuItem>

            </ContextMenu>
        </StackPanel.ContextMenu>
        <Image 
            Source="{Binding ImageURL, Converter={StaticResource StringToImageConverter}}"
            Margin="0,0,2,0"
            Height="25"
            Width="25"/>
        <TextBlock 
            Text="{Binding ServerName}"
            Foreground="White"/>
    </StackPanel>
</HierarchicalDataTemplate>

thanks for the help


回答1:


You can get the TreeViewItem by getting PlacementTarget of ContextMenu which will be StackPanel and its TemplatedParent will be ContentPresenter and its TemplatedParent will be TreeViewItem. So this will work:

CommandParameter="{Binding Path=PlacementTarget.TemplatedParent.TemplatedParent, 
                           RelativeSource={RelativeSource Mode=FindAncestor,
                                            AncestorType={x:Type ContextMenu}}}"

PlacementTarget (StackPanel) --> TemplatedParent (ContentPresenter) --> TemplatedParent (TreeViewItem)


Ideally it's not a good idea to pass UI components to ViewModel. You should pass data i.e. DataContext of TreeViewItem as you can always play with that.

In case you want to pass Server instance i.e. DataContext of TreeviewItem, you can simply do "{Binding}" since MenuItem will inherit it from StackPanel.

CommandParameter="{Binding}"


来源:https://stackoverflow.com/questions/22448749/pass-contextmenu-parent-as-commandparameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!