C#中listView列自动适应缩放的完美效果
在网上搜了很多办法,包括width=-1、-2,效果都不理想。自己摸索了个办法:
1:设计时,先把各列尺寸大体上调好;
2:启动时记下来各列width所占的比例。
public class colSizes : List<double> { }; public colSizes[] grdSizes = new colSizes[3]; public DateTime dBegin = DateTime.Today; //////// loadSizes(grd_ing, ref grdSizes[0]); loadSizes(grd_hege, ref grdSizes[1]); loadSizes(grd_buhege, ref grdSizes[2]); /////////// private void loadSizes(ListView grd, ref colSizes cs) { //记住比例 if (cs == null) cs = new colSizes(); cs.Clear(); double nAll = 0; foreach (ColumnHeader itm in grd.Columns) nAll += itm.Width; foreach (ColumnHeader itm in grd.Columns) cs.Add(itm.Width / nAll); }
3:resize时按比例重新设置一遍各列的width.
private void setAutoSize(ListView grd, colSizes cs) { //自动适应宽度,-1根据内容设置宽度,-2根据标题设置宽度 if (cs == null) return; for (int i = 0; i < Math.Min(cs.Count, grd.Columns.Count); i++) grd.Columns[i].Width = (int)Math.Round(grd.ClientSize.Width * cs[i], 0); } private void FrmView_Resize(object sender, EventArgs e) { setAutoSize(grd_ing, grdSizes[0]); setAutoSize(grd_hege, grdSizes[1]); setAutoSize(grd_buhege, grdSizes[2]); }
效果相当完美,按比例缩放