将TreeViewItem标记传递给事件处理程序c#

时间:2015-11-09 01:14:19

标签: c# wpf treeview

好的,下面是我的代码到目前为止我正在尝试将菜单添加到自定义文件浏览器。现在我正在处理一个新的文件夹按钮,但最终想要在菜单中添加更多项目。我的问题是如何将标签从项目传递到Menu_MouseLeftClick事件处理程序。在此先感谢您的帮助,我提前感谢您。

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];
    }
}

} `

2 个答案:

答案 0 :(得分:0)

使用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
}

答案 1 :(得分:0)

不要手动添加控件(TreeViewItem)。 使用Collection作为视图模型 从treeView ItemsSource属性绑定到集合。 使用DataTemplate将视图模型上的relavent属性绑定到TreeViewItem控件上的依赖项属性。

所有pluming应该来自Xaml文件