Auto size ElementHost to its content

6k views Asked by At

I have a small WPF control that has a TextBlock with TextWrapping set to Wrap. I am trying to host this in an existing WinForms application. I have the ElementHost docked to the top of the form, and I would like to size the height of the ElementHost based on the height that the TextBlock require. Is there any way to accomplish this?

2

There are 2 answers

5
Emond On

The resizing mechanism of WinForms is different from WPF's.

Have you tried setting the AutoSize property of the ElementHost to true?

0
oleksa On

I found the answer here

this is code from the link above:

public System.Windows.Size GetElementPixelSize(UIElement element) 
{ 
    Matrix transformToDevice; 
    var source = PresentationSource.FromVisual(element);
    if (source != null)
        transformToDevice = source.CompositionTarget.TransformToDevice;
    else     
        using (var Hwndsource = new HwndSource(new HwndSourceParameters()))
            transformToDevice = Hwndsource.CompositionTarget.TransformToDevice;


    if (element.DesiredSize == new System.Windows.Size()) 
        element.Measure(new System.Windows.Size(double.PositiveInfinity, double.PositiveInfinity)); 

    return (System.Windows.Size)transformToDevice.Transform((Vector)element.DesiredSize); 
}