У меня есть TreeView
, с ResourceDictionary
, содержащим ContextMenu
, с (в настоящее время) единственным MenuItem
. (Я буду добавлять больше MenuItem
позже.)
Я пытаюсь добавить событие к этому с помощью кода C #. Я знаю, что немного странно хотеть сделать это с помощью кода, а не просто указать его в XAML, но это то, что мне нужно сделать для других требований.
Итак, моя иерархия:
Window
(без имени / ключа)
Grid
(без имени / ключа)
TreeView
(с именем treeView)
ContextMenu
.
MenuItem
Итак, теперь я перехожу к выделенному коду и могу перемещаться по этой иерархии и добавлять обработчик событий.
Есть ли лучший способ сделать это с помощью кода?
Code-Behind
var contextmenu = treeView.TryFindResource("allRequirementGroupsMenu") as ContextMenu;
var mnu_create_reqgrp = contextmenu.Items.OfType<MenuItem>()
.FirstOrDefault(item =>
item.Name == "mnuItem_CreateRequirementGroup");
if(mnu_create_reqgrp != null)
mnu_create_reqgrp.Click += RequirementGroup_Create_Click;
XAML
<Window x:Class="MyApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MyApp"
mc:Ignorable="d"
Title="MainWindow" Height="800" Width="1600">
<Grid>
<TreeView x:Name="treeView">
<TreeView.Resources>
<ResourceDictionary>
<ContextMenu x:Key="allRequirementGroupsMenu"
StaysOpen="True">
<MenuItem Header="Create Requirement Group"
Name="mnuItem_CreateRequirementGroup" />
</ContextMenu>
</ResourceDictionary>
</TreeView.Resources>
<TreeViewItem Header="Vendors"
ItemsSource="{Binding Vendors}" />
<TreeViewItem Header="Checklists"
ItemsSource="{Binding Checklists}" />
<TreeViewItem Header="Requirement Groups"
ItemsSource="{Binding RequirementGroups}"
ContextMenu="{StaticResource allRequirementGroupsMenu}" />
<TreeViewItem Header="Ungrouped Items"
ItemsSource="{Binding UngroupedItems}" />
</TreeView>
</Grid>
</Window>