标签中的路径显示
时间:2020-03-05 18:41:38 来源:igfitidea点击:
是否有任何自动方法来修剪.NET中的路径字符串?
例如:
C:\Documents and Settings\nick\My Documents\Tests\demo data\demo data.emx
变成
C:\Documents...\demo data.emx
如果将它内置到Label类中,那就特别酷了,我似乎还记得,虽然找不到它!
解决方案
回答
我们在标签上的想法是,如果长度大于宽度(未设置为自动尺寸),它将放置...
c:\Documents and Settings\nick\My Doc...
如果有支持,它可能在System.IO中的Path类上
回答
我们可以使用System.IO.Path.GetFileName方法,并将该字符串添加到缩短的System.IO.Path.GetDirectoryName字符串中。
回答
不难写自己:
public static string TrimPath(string path) { int someArbitaryNumber = 10; string directory = Path.GetDirectoryName(path); string fileName = Path.GetFileName(path); if (directory.Length > someArbitaryNumber) { return String.Format(@"{0}...\{1}", directory.Substring(0, someArbitaryNumber), fileName); } else { return path; } }
我想我们甚至可以将其添加为扩展方法。
回答
将TextRenderer.DrawText与TextFormatFlags.PathEllipsis标志一起使用
void label_Paint(object sender, PaintEventArgs e) { Label label = (Label)sender; TextRenderer.DrawText(e.Graphics, label.Text, label.Font, label.ClientRectangle, label.ForeColor, TextFormatFlags.PathEllipsis); }
Your code is 95% there. The only problem is that the trimmed text is drawn on top of the text which is already on the label.
是的,谢谢,我意识到了这一点。我的目的只是演示" DrawText"方法的使用。我不知道我们是要为每个标签手动创建事件,还是要在继承的标签中重写OnPaint()方法。不过,感谢我们分享最终解决方案。
回答
@ lubos hasko代码在那里95%。唯一的问题是,修剪后的文本绘制在标签上已经存在的文本之上。这很容易解决:
Label label = (Label)sender; using (SolidBrush b = new SolidBrush(label.BackColor)) e.Graphics.FillRectangle(b, label.ClientRectangle); TextRenderer.DrawText( e.Graphics, label.Text, label.Font, label.ClientRectangle, label.ForeColor, TextFormatFlags.PathEllipsis);