EnsureVisible for ListViewSubItem
在 ListView 中水平滚动以确保子项可见
介绍
它扩展了 ListView
控件,并添加了一个 EnsureVisible
方法,用于水平滚动到子项。
背景
我经常使用 Code Project 来寻找好的示例,但没有找到这个的示例。所以我想回馈一些东西。
使用代码
用于滚动 ListView 的原生 Windows 消息是
const Int32 LVM_FIRST = 0x1000;
const Int32 LVM_SCROLL = LVM_FIRST + 20;
[DllImport("user32")]
static extern IntPtr SendMessage(IntPtr Handle, Int32 msg, IntPtr wParam,
IntPtr lParam);
private void ScrollHorizontal(int pixelsToScroll)
{
SendMessage(this.Handle, LVM_SCROLL, (IntPtr)pixelsToScroll,
IntPtr.Zero);
}
要滚动到的项目的公共方法如下
/// <summary>
/// Ensure visible of a ListViewItem and SubItem Index.
/// </summary>
/// <param name="item"></param>
/// <param name="subItemIndex"></param>
public void EnsureVisible(ListViewItem item, int subItemIndex)
{
if (item == null || subItemIndex > item.SubItems.Count - 1)
{
throw new ArgumentException();
}
// scroll to the item row.
item.EnsureVisible();
Rectangle bounds = item.SubItems[subItemIndex].Bounds;
// need to set width from columnheader, first subitem includes
// all subitems.
bounds.Width = this.Columns[subItemIndex].Width;
ScrollToRectangle(bounds);
}
/// <summary>
/// Scrolls the listview.
/// </summary>
/// <param name="bounds"></param>
private void ScrollToRectangle(Rectangle bounds)
{
int scrollToLeft = bounds.X + bounds.Width + MARGIN;
if (scrollToLeft > this.Bounds.Width)
{
this.ScrollHorizontal(scrollToLeft - this.Bounds.Width);
}
else
{
int scrollToRight = bounds.X - MARGIN;
if (scrollToRight < 0)
{
this.ScrollHorizontal(scrollToRight);
}
}
}
}
历史
- 2008年9月30日:初始发布