listview控件
I was recently working on a project that uses a list view control. I had to dynamically add items based on a configuration file so I could not set the height of the list view at design time unless I wanted scroll bars. For my application, I wasn't expecting a large amount of items. Therefore, I wanted to always size the list view to just the right amount so that it would not show a vertical scroll bar. Unfortunately, there is no autosize property of the list view control. I was able to write a series of extension methods that let you auto size the list view control. This could be done by inheriting from the list view control instead. I chose the extension method model for this article so that you don't have to add a control to your tool box.
我最近正在研究一个使用列表视图控件的项目。 我必须根据配置文件动态添加项目,因此除非设计滚动条,否则在设计时无法设置列表视图的高度。 对于我的应用程序,我没想到会有很多东西。 因此,我想始终将列表视图的大小调整为适当的大小,以使其不会显示垂直滚动条。 不幸的是,列表视图控件没有autosize属性。 我能够编写一系列扩展方法,使您可以自动调整列表视图控件的大小。 这可以通过从列表视图控件继承来完成。 我为本文选择了扩展方法模型,因此您不必在控件框中添加控件。
For maximum control, I separated the height and width functionality and then included an all encompassing method that calls both. For added flexibility, I allow you to set the number of items you want to display. To autosize it fully, pass in the number of items that the list view control contains.
为了最大程度地控制,我分离了高度和宽度功能,然后包括了一个同时调用两者的包围方法。 为了增加灵活性,我允许您设置要显示的项目数。 若要完全自动调整大小,请传入列表视图控件包含的项目数。
1.创建扩展方法框架 (1. Create the Extension Method Framework)
using System;
using System.Windows.Forms;
namespace ListViewExtensionMethods
{
public static class ListViewExtensions
{
public static void AutoSizeControlHeight ( this ListView lv, int maxItemsToShow, bool adjustForHorizontalScrollBar)
{
}
public static void AutoSizeControlWidth ( this ListView lv, bool adjustForVerticalScrollBar )
{
}
public static void AutoSizeControl ( this ListView lv, int maxItemsToShow, bool adjustForHorizontalScrollBar, bool adjustForVerticalScrollBar )
{
}
}
}
As you can see, we've created 3 functions, one for each dimension and then one that brings it all together. We'll first work with the Height function
如您所见,我们创建了3个功能,每个功能一个,然后将所有功能都整合在一起。 我们将首先使用“高度”功能
Within the height method
内高法
2.声明我们的变量 (2. Declare our variables)
int positionBefore = 0;
int positionAfter = 0;