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?
            Asked
            
        
        
            Active
            
        
            Viewed 5,958 times
        
    2 Answers
5
            
            
        The resizing mechanism of WinForms is different from WPF's.
Have you tried setting the AutoSize property of the ElementHost to true?
        Emond
        
- 50,210
 - 11
 - 84
 - 115
 
- 
                    That was my first thought, but it doesn't do anything. – Brian Kohrs Feb 25 '11 at 21:36
 - 
                    Did you have a look at this post: http://stackoverflow.com/questions/1086184/resize-elementhost-to-size-of-the-hosted-xmal-usercontrol – Emond Feb 25 '11 at 21:39
 - 
                    4Setting the `AutoSize` property for the `ElementHost` as well as the `AutoSize` for the control that contains the `ElementHost`, in my case a `Form`, works for me. – Mike de Klerk Oct 30 '13 at 06:21
 - 
                    @MikedeKlerk Thanks, that works like a charm, in my case with the `ElementHost` contained within a `Panel` – rucamzu Jan 23 '18 at 12:27
 - 
                    @MikedeKlerk in my case im setting "AutoSize" to both the "ElementHost" and "Form" Onloading window in first time Form size greater then my control size – Sharan RM Jul 26 '21 at 11:04
 
0
            
            
        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); 
} 
        oleksa
        
- 3,688
 - 1
 - 29
 - 54