I am working on a small project which needs to add the treeview items to a listbox, I managed to do this with my treeview:
<HierarchicalDataTemplate DataType="{x:Type data:Category}" ItemsSource="{Binding Path=Products}">
<TextBlock Text="{Binding Path=CategoryName}" AllowDrop="True"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type data:Product}" >
<TextBlock Text="{Binding Path=ModelName}" AllowDrop="True"/>
</HierarchicalDataTemplate>
And i also tried to add a contextmenu to the treeviewitem like this:
<TreeView x:Name="tv_Project" Margin="5">
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<EventSetter Event="TreeViewItem.PreviewMouseRightButtonDown" Handler="TreeViewItem_PreviewMouseRightButtonDown"/>
</Style>
</TreeView.ItemContainerStyle>
<TreeView.ContextMenu>
<ContextMenu>
<MenuItem Header="Add To Project" Click="MenuItem_OnClick" />
</ContextMenu>
</TreeView.ContextMenu>
</TreeView>
The Problem is i just want to add the Eventto my child-node(in my project ModelName) not including parent-node(in my project CategoryName), What should i do?Thanks!
Here is my backend code:
private void TreeViewItem_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
var treeViewItem = VisualUpwardSearch<TreeViewItem>(e.OriginalSource as DependencyObject) as TreeViewItem;
if (treeViewItem != null)
{
treeViewItem.Focus();
e.Handled = true;
}
}
static DependencyObject VisualUpwardSearch<T>(DependencyObject source)
{
while (source != null && source.GetType() != typeof(T))
source = VisualTreeHelper.GetParent(source);
return source;
}
private void MenuItem_OnClick(object sender, RoutedEventArgs e)
{
var item = this.tv_Project.SelectedItem;
if (item != null)
{
lb_Configuration.Items.Add(item);
}
}