wpf - Binding details of a TreeViewItem to a ContextMenu -
i have contextmenu appears on right click of treeviewitem. pass couple of details treeviewitem context menu.
how starting here:
xaml
<treeview x:class="myapp.treecontrol" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:ignorable="d" d:designheight="300" d:designwidth="300" previewmouseleftbuttondown="treeview_previewmouseleftbuttondown" previewmousemove="treeview_previewmousemove" previewmouserightbuttondown="treecontrol_onpreviewmouserightbuttondown"> <treeview.contextmenu> <contextmenu> <menuitem name="dataitem1" header="property1"></menuitem> <menuitem name="dataitem2" header="property2"></menuitem> <separator/> <menuitem name="taskitem" header="tasks" click="taskitem_onclick"></menuitem> </contextmenu> </treeview.contextmenu> </treeview>
i words property1
, property2
replaced values of properties in treeviewitem right clicked, sort of : {binding selecteditem.property1}
code: (basically highlight clicked node)
private void treecontrol_onpreviewmouserightbuttondown(object sender, mousebuttoneventargs e) { treeviewitem treeviewitem = visualupwardsearch(e.originalsource dependencyobject); if (treeviewitem != null) { treeviewitem.isselected = true; treeviewitem.focus(); e.handled = true; } }
the first thing need data bind menuitem.header
properties object set contextmenu.datacontext
:
<contextmenu datacontext="{binding placementtarget.tag, relativesource={ relativesource self}}"> <menuitem name="dataitem1" header="{binding property1}"></menuitem> <menuitem name="dataitem2" header="{binding property2}"></menuitem> <separator/> <menuitem name="taskitem" header="tasks" click="taskitem_onclick"></menuitem> </contextmenu>
what placementtarget.tag
, hear ask. looking @ contextmenu.placementtarget
property page on msdn, see it:
gets or sets
uielement
relativecontextmenu
positioned when opens.
in plain english, means the ui element has contextmenu
applied it. tag
property free property of type object
can put into. in case, we're going put contextmenu.datacontext
value in there because can't set directly, because contextmenu
not part of general ui visual tree:
now didn't show code apply contextmenu
treeviewitem
, in same place, need set tag
property object want set contextmenu.datacontext
value. pass in here , take out in contextmenu
shown in code example.
for more information, please take @ answers contextmenu.placementtarget not getting set, no idea why , add context menu in datagrid, how select item value questions here on stack overflow.
Comments
Post a Comment