如何以编程方式将ToolstripDropDownButton添加到带有下拉菜单的工具条(C#Winforms)

时间:2016-06-25 00:05:49

标签: c# winforms

我有一个工具条,其中包含代表目录中找到的文件夹的toolstripdropdownbuttons。我想为每个toolstripdropdownbutton提供一个下拉菜单,以包含找到的子文件夹。一个例子是Internet Explorer链接栏我尝试了以下代码,但我不太清楚如何去做(见图) Links Bar Example

我尝试过的代码:

        private void populateLinks()
    {
        linksToolStrip.Items.Clear();
        DirectoryInfo linksFolder = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Favorites) + "\\Links");
        foreach (DirectoryInfo linksDirectory in linksFolder.GetDirectories())
        {
            Image favImage = Properties.Resources.Folder;
            ToolStripDropDownButton button = new ToolStripDropDownButton();
            button.Text = Truncate(linksDirectory.Name, 22);
            button.ToolTipText = linksDirectory.Name + "\nDate Created: " + Directory.GetCreationTime(linksDirectory.FullName);
            button.Image = favImage;
            button.Tag = linksDirectory.FullName;
            linksToolStrip.Items.Add(button);
            populateLinksFolders(linksDirectory, button.DropDown);

        }

private void populateLinksFolders(DirectoryInfo subdirectory, ToolStripDropDown tsdd)
    {
        foreach (DirectoryInfo directory in subdirectory.GetDirectories())
        {
            populateLinksFolders(directory, ?) //<- Everything tried here fails
        }
    }

我该如何做到这一点?

1 个答案:

答案 0 :(得分:0)

您需要传递ToolStripDropDownButton,然后使用DropDownItems属性添加子项。

populateLinksFolders(linksDirectory, button);

然后:

private void populateLinksFolders(DirectoryInfo subdirectory, ToolStripDropDownButton tsddb)
{
    foreach (DirectoryInfo directory in subdirectory.GetDirectories())
    {
        ToolStripDropDownButton button = new ToolStripDropDownButton(directory.Name);
        tsddb.DropDownItems.Add(button);
        populateLinksFolders(directory, button);
    }
}