3

我使用 Caliburn Micro 将我的分层树视图完美地绑定到我的 ViewModel。(ViewModel 有一个 Items 属性,它返回一个 ObservableCollection - 树视图被命名为这个 Items 属性 - 绑定没有问题)。

但是,问题出现在上下文菜单中。菜单在树节点表示的对象的实例上触发一个方法。我想要实现的是让菜单在我的根 ViewModel 上触发一个方法,将由单击的树节点表示的对象的实例作为参数传递给它。这是我的 XAML:

<HierarchicalDataTemplate DataType="{x:Type m:TaskGrouping}" 
                                      ItemsSource="{Binding Children}">
                    <Label Content="{Binding Name}"
                           FontWeight="Bold">
                        <Label.ContextMenu>
                            <ContextMenu>
                                <MenuItem Header="Add New SubFolder"
                                          cal:Message.Attach="AddNewSubfolder" />
                                <MenuItem Header="Remove this folder"
                                          cal:Message.Attach="RemoveFolder" />
                            </ContextMenu>
                        </Label.ContextMenu>
                    </Label>
                </HierarchicalDataTemplate>

为了实现我想要的,我需要对我的 XAML 进行哪些更改?

4

1 回答 1

4

ContextMenus与其他所有东西都位于一个单独的视觉树中 - 使绑定正确可能会很痛苦(我经常有 10-15 分钟的时间与它们上的绑定进行斗争以使它们正确!)

您已经Message.Attach设置了附加属性,您需要做的就是确保操作目标指向 VM 而不是数据项。您可以使用Action.TargetWithoutContext来指定操作的目标(CM 将使用DataContext

您还需要获得一个指向另一个可视化树的绑定路径 - 尝试使用RelativeSource绑定 -ContextMenu还有一个名为的属性PlacementTarget,它应该指向ContextMenu附加到的元素

所以可能:

cal:Action.TargetWithoutContext="{Binding DataContext, RelativeSource={RelativeSource AncestorType=Label}}"

或者

cal:Action.TargetWithoutContext="{Binding PlacementTarget.DataContext}"

您可能需要进行实验,因为我经常第一次就几乎正确!

OP(Shawn)编辑:这最终对我有用:

<Label Content="{Binding Name}"
                               Tag="{Binding DataContext, ElementName=LayoutRoot}">
                            <Label.ContextMenu>
                                <ContextMenu
                                    cal:Action.TargetWithoutContext="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
                                    <MenuItem Header="Run Task Now" cal:Message.Attach="SomeRootViewModelMethod($dataContext)" />
于 2013-04-03T14:14:08.820 回答