Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

c# - CommandParameters in ContextMenu in WPF

I have a scenario where I have a WPF TreeView control that has an HierarchicalDataTemplate for its items. Now inside the HierarchicalDataTemplate, I have a Label and the Label has a ContextMenu with a menuitem for Delete. The Delete menuitem is bound to a Command called DeleteCommand which is a part of the class that has been set as the DataType of the HierarchicalDataTemplate.

Now, I want to pass the TreeView control in the CommandParameters of the ContextMenu's Delete menuitem's DeleteCommand so that I can handle the selection of the TreeViewItems on the deletion of the currently selected item.

But if I bind the CommandParameters as the {Binding ElementName=TreeViewName} or whatever for that matter, it is always null unless the binded element is a property in the DataContext.

Can anyone help me with a solution because I think, I have tried all the possible things such as RelativeSource and AncestorType etc but its always null. To me, it looks like either a limitation or a bug in the framework.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that the ContextMenu is at the root of its own visual tree, so any RelativeSource.FindAncestor bindings won't go past the ContextMenu.

One solution is to use the PlacementTarget property to set up a two-stage binding from your Label:

<Label Tag="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={
    x:Type TreeView}}}">
    <Label.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Delete" Command="{x:Static local:Commands.DeleteCommand}"
                CommandParameter="{Binding PlacementTarget.Tag, RelativeSource={
                RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}"/>
        </ContextMenu>
    </Label.ContextMenu>
</Label>

This is quite hacky, however. You're better off setting the CommandTarget property of your MenuItem to the ContextMenu's PlacementTarget and having the command handler on your TreeView. This means you won't have to pass the TreeView around.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...