使用WPF和MVVM处理TreeViews上下文菜单

时间:2017-04-24 11:24:34

标签: wpf mvvm caliburn.micro

我有一个显示TreeView的应用程序。 TreeView有一个上下文菜单。我使用Caliburn.Micro作为MVVM框架。

cal:Message.Attach="[Event Click]=[Action Remove()]"是必需的,以便在单击ContextMenu-Item时发生某些事情。此行使Caliburn.Micro在TreeItem的ViewModel中搜索名为Remove的方法。

但是我希望点击ContextMenu项目会调用方法删除屏幕的ViewModel。怎么做?

<TreeView.ItemTemplate>
    <HierarchicalDataTemplate ItemsSource="{Binding Children}">
        <TextBlock Text="{Binding Name}">
            <TextBlock.ContextMenu>
                <ContextMenu>
                    <MenuItem cal:Message.Attach="[Event Click]=[Action Remove()]" Name="Remove" Header="Remove item" />
                </ContextMenu>
            </TextBlock.ContextMenu>
        </TextBlock>
    </HierarchicalDataTemplate>
</TreeView.ItemTemplate>

2 个答案:

答案 0 :(得分:1)

试试这个:

<TreeView.ItemTemplate>
    <HierarchicalDataTemplate ItemsSource="{Binding Children}">
        <TextBlock Text="{Binding Name}">
            <TextBlock.ContextMenu>
                <ContextMenu>
                    <MenuItem Tag="{Binding RelativeSource={RelativeSource AncestorType=TreeView}}"
                              cal:Action.TargetWithoutContext="{Binding Path=PlacementTarget.Tag.DataContext, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"
                              cal:Message.Attach="[Event Click]=[Action RemoveResource()]" Name="Remove" Header="Remove item" />
                </ContextMenu>
            </TextBlock.ContextMenu>
        </TextBlock>
    </HierarchicalDataTemplate>
</TreeView.ItemTemplate>

请参阅我的回答以获取更多信息:

Caliburn Micro Action inside ItemContainerStyle - No target found for method

答案 1 :(得分:0)

有人遇到类似的问题“Bubbling” events from bound viewmodel goes to parent

根据作者本人Bind a Command to a Button inside a ListView with Caliburn.Micro

所以按惯例或者像这样召唤:

<i:Interaction.Triggers>
    <i:EventTrigger EventName="Click">
        <cal:ActionMessage MethodName="{Binding Name}" />
    </i:EventTrigger>
</i:Interaction.Triggers>