将TreeViewItem标记传递给事件处理程序c#
本文关键字:事件处理 程序 TreeViewItem | 更新日期: 2023-09-27 18:21:04
好的,下面是我的代码,到目前为止,我正在尝试将菜单添加到自定义文件浏览器中。现在我正在制作一个新的文件夹按钮,但最终想在菜单中添加更多的项目。我的问题是如何首先将标记从项目传递到MenuMouseLeftClick事件处理程序。提前感谢你的帮助我是新的提前感谢。
using System.Windows;
using System.Windows.Controls;
using System.IO;
using System.Collections.Generic;
using System;
namespace TreeViewWithMenu
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
//Create Objects and Handlers
InitializeComponent();
PopTree();
SetMenu();
this.treeView.MouseRightButtonDown += TreeView_MouseRightButtonDown;
this.menu.MouseLeftButtonDown += Menu_MouseLeftButtonDown;
}
private void TreeView_MouseRightButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
//Make Folder Visable
this.menu.Visibility = Visibility.Visible;
}
private void SetMenu()
{
//Set Menu for new Folder
MenuItem MeItem = new MenuItem();
MeItem.Header = "New Folder";
MeItem.Tag = "New Folder";
menu.Items.Add(MeItem);
menu.Visibility = Visibility.Hidden;
}
private void Menu_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
//Create New FOlder
Directory.CreateDirectory("");
}
internal void PopTree()
{
//Populate Tree
List<string> CleanDirs = new List<string>();
string [] Dirs = Directory.GetDirectories(Environment.GetFolderPath(Environment.SpecialFolder.Desktop));
string temp;
foreach (string dir in Dirs)
{ temp = SplitPath(dir); CleanDirs.Add(temp.ToUpper()); }
foreach(var ShowIn in CleanDirs)
{
TreeViewItem TreeViewDirectory = new TreeViewItem();
TreeViewDirectory.Tag = ShowIn;
TreeViewDirectory.Header = ShowIn;
TreeViewDirectory.Focusable = true;
this.treeView.Items.Add(TreeViewDirectory);
}
}
private string SplitPath(string path)
{
string[] temp = path.Split('''');
return temp[temp.Length - 1];
}
}
}`
使用SelectedItem
属性访问TreeView
中当前选定的项目,该项目应与您右键单击的项目相同。
private void TreeView_MouseRightButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (treeView.SelectedItem == null)
return;
var selectedTag = ((TreeViewItem)treeView.SelectedItem).Tag;
// do something with the tag
}
不要手动添加控件(TreeViewItem)。使用集合作为视图模型从treeView ItemsSource属性绑定到集合。使用DataTemplate将视图模型上的relavent属性绑定到TreeViewItem控件上的依赖项属性。
所有的填充都应该来自Xaml文件