简体   繁体   中英

Best way for acquiring an element's height

The code gets the desired height for an element given a Datatemplate and the object to be bound to content. However, this is really slow. Does anyone have an alternative, or an idea how to optimize this code.

public static Double GetDesiredHeight(Object content, DataTemplate  dataTemplate)
{
        try
        {
            ContentPresenter element = new ContentPresenter
            {
                Content = content,
                ContentTemplate = dataTemplate,
            };

            element.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
            var result = element.DesiredSize.Height;
            element.ContentTemplate = null;
            return result;
        }
        catch (Exception)
        {
            return 0;
        }
}

have you tried using ActualHeight property instead of Height property?

try to change this line:

var result = element.DesiredSize.ActualHeight;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM