WPF: How to auto-size WebBrowser inside a Popup?

2020-04-16 04:37发布

问题:

I have a Popup with a WebBrowser inside (see code below). The WebBrowser have MaxWidth = "800". I want auto-size the height of WebBrowser to its content height after it load website, so it dont need vertical ScrollBar.

I tried set Height = "Auto" or MaxHeight = "5000", but I dont get right result.

Can you help me how to do it? Thank you very much!

    <Popup Name="popup1" VerticalOffset="3">
        <Border BorderThickness="1">
            <DockPanel>
                <ScrollViewer MaxHeight="700" VerticalScrollBarVisibility="Auto">
                    <WebBrowser Name="wb1" MaxWidth="800"/>
                </ScrollViewer>
            </DockPanel>
        </Border>
    </Popup>

回答1:

Here is the solution:

<Popup x:Name="Popup" Width="800">
    <Border BorderThickness="1">
        <WebBrowser
            x:Name="WebBrowser"
            LoadCompleted="WebBrowser_OnLoadCompleted"
            ... />
    </Border>
</Popup>

Handler:

private void WebBrowser_OnLoadCompleted(object sender, NavigationEventArgs e) {
    this.Popup.Height = (int) (this.WebBrowser.Document as dynamic).body.scrollHeight + 20;
}