WPF DataGrid Row height Row height automatic calculation makes each row of rows highly adaptive text

Source: Internet
Author: User
Tags wpf datagrid

The row height of the DataGrid for WPF is either auto or fixed: But the trouble is that each row is the same height.

The Loadingrow event of the DataGrid is required when you need to dynamically adjust the height of the row by content (mostly wrap-wrapped textbox or TextBlock).

Refer to two pages:

Http://stackoverflow.com/questions/9264398/how-to-calculate-wpf-textblock-width-for-its-known-font-size-and-characters

Http://www.codeproject.com/Articles/5521/Advanced-DataGrid-sizing

Code comments in detail, not detailed.

The code is as follows:

 private void Dglist_loadingrow (object sender, DataGridRowEventArgs e) {e.row.height = 30; Rough calculation of row height.            For better display effect ContentInfo info = (contentinfo) e.row.datacontext; if (info = null) {//calculates the maximum length of text string maxlengthstring = info.name1.Length > I Nfo.name2.Length?                info.name1:info.name2; Gets the width of the text box for the wrapping, which is the actual width of the textbox or TextBlock inside the template, double textboxwidth = (this.                                 ACTUALWIDTH-300)/2;     var formattedtext = new FormattedText (maxlengthstring, CultureInfo.CurrentUICulture, Flowdirection.lefttoright, New Typeface (New FontFamily ("Microsoft Jas"), Fontstyles.normal, Fontweights.normal, fontstretches.normal), brushes.b                lack);                Double calculateheight = formattedtext.height * (formattedtext.width/textboxwidth); E.row.height = > calculateheight?            30:calculateheight; }        }

Effects (each row is different in height, adaptive):

Reprint please indicate the source, thank you. If you have any questions, please contact: [Email protected]

WPF DataGrid Row height Row height automatic calculation makes each row of rows highly adaptive text

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.