wpf winforms_如何自动调整WinForms DataGrid中的列大小(自动调整大小)?

wpf winforms

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());
            }
        }

(Thanks to

私有无效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());
}
}

(感谢 Patrick Cauldwell for his help) Patrick Cauldwell的帮助)

翻译自: https://www.hanselman.com/blog/how-do-i-automatically-size-autosize-columns-in-a-winforms-datagrid

wpf winforms

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值