0

I have an ElementHost which contains an WPF user control.

For some reason that I don't know, the ElementHost is not being resized to the user control when it changes its height.

My ElementHost has the property AutoSize set to True and the Dock property set to DockStyle.Fill. Also my WPF user control that I bound to the ElementHost.Child has also the Autosize property set to True.

When my WPF changes its height dynamically, the ElementHost does not resize accordingly to have the same height as the WPF user control.

I have been searching a lot in google and I got with this interesting post and also with this one.

There is discussed about do the following:

  1. Override the MeasureOverride method
  2. After the measurement is calculated, use PresentationSource.From(visual).CompositionTarget.TransformToDevice.Transform(point) to get the device coordinates
  3. Update ElementHost.Size.

So in one of the answers of that post I found the method that calculates the size which is this. Here it is:

    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);
    }

Now I am trying to follow the 3 steps above indicated, in order to update the ElementHost size. So first, I override the MeasureOverride method in my xaml.cs wpf user control, convert the size from WPF coordinates to device coordinates and finally I am trying to update the ElementHost.Size:

    protected override Size MeasureOverride(Size constraint)
    {
        // within my wpf control I have a reference to ElementHost so I can do below
        // myDlgHost is the name that my wpf user control has - I have set it through x:Name -
        ElementHost.Size = this.GetElementPixelSize(this.myDlgHost);

        return base.MeasureOverride(constraint);
    }

But a compilation error appears when trying to update the ElementHost.Size, it says:

Cannot implicitly convert type 'System.Windows.Size' to 'System.Drawing.Size'

So anyone can indicate me how can I convert the size from WPF coordinates to device coordinates and update the elementhost size?

Willy
  • 9,848
  • 22
  • 141
  • 284
  • 1
    If it is just about the compiler error, create a new System.Drawing.Size with the Width and Height values of the System.Windows.Size returned from GetElementPixelSize. – Clemens Jan 27 '23 at 07:32

0 Answers0