gpt4 book ai didi

c# - .NET 中带有滚动条的下拉菜单

转载 作者:太空狗 更新时间:2023-10-29 20:03:52 25 4
gpt4 key购买 nike


我正在尝试制作一个类似于 Windows Vista/7 浏览器中使用的 Windows 资源管理器中的面包屑栏的用户控件。

但是,当我显示包含许多子项的面包屑导航的下拉菜单时,我会得到一个很长的列表,有时会超过屏幕大小。
然而,在 Windows Vista/7 示例中,一次最多显示 18 个项目,当子项目的数量超过此数量 (18) 时,右侧会出现一个滚动条。

我想知道是否有人知道复制微软所做的事情的方法。
[即,如何在具有自动滚动功能的控件中放置下拉菜单。]



谢谢。
亚历克斯

最佳答案

Windows 7/Vista 面包屑看起来类似于 ListView 。下图给出了我的意思的示例(在 windows xp 上)(单击按钮出现列表):

Windows 7 breadcrumb sample

这是获取它的代码:

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
var button = sender as Button;

// create fake items list
List<string> strings = new List<string>();
for (int i = 0; i < 36; i++)
strings.Add("ITEM " + (i+1));
var listViewItems = strings.Select(x => new ListViewItem(x, 0)).ToArray();

// create a new list view
ListView listView = new ListView();
listView.View = View.SmallIcon;
listView.SmallImageList = imageList1;
listView.MultiSelect = false;

// add items to listview
listView.Items.AddRange(listViewItems);

// calculate size of list from the listViewItems' height
int itemToShow = 18;
var lastItemToShow = listViewItems.Take(itemToShow).Last();
int height = lastItemToShow.Bounds.Bottom + listView.Margin.Top;
listView.Height = height;

// create a new popup and add the list view to it
var popup = new ToolStripDropDown();
popup.AutoSize = false;
popup.Margin = Padding.Empty;
popup.Padding = Padding.Empty;
ToolStripControlHost host = new ToolStripControlHost(listView);
host.Margin = Padding.Empty;
host.Padding = Padding.Empty;
host.AutoSize = false;
host.Size = listView.Size;
popup.Size = listView.Size;
popup.Items.Add(host);

// show the popup
popup.Show(this, button.Left, button.Bottom);
}
}

编辑:

要获取选中的item,一种方式如下:

// change some properties (for selection) and subscribe the ItemActivate 
// event of the listView
listView.HotTracking = true;
listView.Activation = ItemActivation.OneClick;
listView.ItemActivate += new EventHandler(listView_ItemActivate);


// the click on the item invokes this method
void listView_ItemActivate(object sender, EventArgs e)
{
var listview = sender as ListView;
var item = listview.SelectedItems[0].ToString();
var dropdown = listview.Parent as ToolStripDropDown;
// unsubscribe the event (to avoid memory leaks)
listview.SelectedIndexChanged -= listView_ItemActivate;
// close the dropdown (if you want)
dropdown.Close();

// do whatever you want with the item
MessageBox.Show("Selected item is: " + item);
}

关于c# - .NET 中带有滚动条的下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3171640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com