wpf winforms
Apparently this is, like, the problem for the ages or something, but noone on this planet has come up with a way to automatically size the columns in a DataGrid. Sure, there's all sorts of pyscho ways that involve measuring the length of strings in DataSets with the Graphics context, yada yada. But, since I'm binding strongly-typed Object Collections to DataGrids in WinForm apps, that doesn't work for me (and it's a little over the top, IMHO).
显然,这就像是年龄问题之类的问题,但这个星球上没有人想出一种自动调整DataGrid中列大小的方法。 当然,有很多pyscho方法,它们涉及使用Graphics上下文yada yada测量数据集中的字符串长度。 但是,由于我将强类型的对象集合绑定到WinForm应用程序中的DataGrid,所以这对我不起作用(恕我直言,恕我直言)。
So, I thought about it like this:
所以,我这样想:
- If you double click on the little splitter between columns they will autosize. 如果双击列之间的小分隔符,它们将自动调整大小。
- Therefore, the code to autosize has been written for me; no need to measure strings, etc. 因此,已经为我编写了自动调整大小的代码。 无需测量琴弦等
How do I force a double click? No, wait, wrongheadedness, how do I call whatever THEY call when a double click happens?
如何强制双击? 不,等等,头疼,双击时我怎么称呼他们?
So, I reflectored into DataGrid.OnMouseDown and saw their custom HitTest calls a private ColAutoResize. Ah, bingo.
因此,我对DataGrid.OnMouseDown进行了反思,并看到他们的自定义HitTest调用了私有ColAutoResize 。 啊,宾果
If you're going to 'sin' do it with style - do it with Reflection.
如果您要“罪恶”,请使用样式-使用反射。
private void dgLogging_DataSourceChanged(object sender, System.EventArgs e)
{
try
{
Type t = dgLogging.GetType();
MethodInfo m = t.GetMethod("ColAutoResize",BindingFlags.NonPublic);
for (int i = dgLogging.FirstVisibleColumn; (i < dgLogging.VisibleColumnCount); i++)
{
m.Invoke(dgLogging, new object[]{i});
}
}
catch (Exception ex)
{
System.Diagnostics.Trace.Write("Failed Resizing Columns: " + ex.ToString());
}
}
私有无效dgLogging_DataSourceChanged(对象发送者,System.EventArgs e)
{
尝试
{
类型t = dgLogging.GetType();
MethodInfo m = t.GetMethod( “ ColAutoResize” ,BindingFlags.NonPublic);
为( int i = dgLogging.FirstVisibleColumn;(i <dgLogging.VisibleColumnCount); i ++)
{
m.Invoke(dgLogging,新对象[] {i});
}
}
抓住(前例外)
{
System.Diagnostics.Trace.Write( “调整大小列失败:” + ex.ToString());
}
}
翻译自: https://www.hanselman.com/blog/how-do-i-automatically-size-autosize-columns-in-a-winforms-datagrid
wpf winforms