Auto size ElementHost to its content
Asked Answered
W

2

8

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?

Wreath answered 25/2, 2011 at 19:24 Comment(0)
K
5

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

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

Karlene answered 25/2, 2011 at 20:25 Comment(5)
That was my first thought, but it doesn't do anything.Wreath
Did you have a look at this post: #1086684Karlene
Setting 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.Polyneuritis
@MikedeKlerk Thanks, that works like a charm, in my case with the ElementHost contained within a PanelArtois
@MikedeKlerk in my case im setting "AutoSize" to both the "ElementHost" and "Form" Onloading window in first time Form size greater then my control sizeUlrikaumeko
M
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); 
} 
Morse answered 19/1, 2015 at 16:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.