How do I work around the ActiveX WebBrowser flaw in a WPF Window that AllowsTransparency=true

StackOverflow https://stackoverflow.com/questions/23529824

  •  17-07-2023
  •  | 
  •  

سؤال

I'm building an application that I've created a custom skin for all windows and dialogs; each window has a customized "X" button in the upper right-hand corner, among other things. I've essentially set WindowStyle=None and AllowsTransparency=True. I have a tab control within this window, and one of the tabs has a WPF WebBrowser Control. When I first started out, I didn't have custom skinning on the windows, and the web browser controls worked as expected. Once I skinned the windows and set AllowsTransparency=True, and the WebBrowser Controls just show a blank white page now.

I understand that there is some sort of said flaw in ActiveX that is causing this, since the WebBrowser WPF Control is essentially a wrapper. Can someone please provide a decent solution or a decent workaround for this issue?

The following is my xaml and screenshots. I've simplified it down into a simple Window for the sake of this post:

This works: (AllowTransparency=False)

<Window x:Class="AllowTransparencyIssue.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" 
        Height="500" 
        Width="700"
        AllowsTransparency="False"
        WindowStartupLocation="CenterScreen"
        WindowStyle="SingleBorderWindow"

        >
    <Border BorderBrush="Blue" BorderThickness="3">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition />
            </Grid.RowDefinitions>

            <Button Grid.Row="0" HorizontalAlignment="Right" Click="Button_Click">Close Window</Button>

            <TabControl Grid.Row="1">

                <TabItem Header="StartPage.com">
                    <TabItem.Content>
                        <WebBrowser Source="http://www.startpage.com" />
                    </TabItem.Content>
                </TabItem>

                <TabItem Header="Google.com">
                    <TabItem.Content>
                        <WebBrowser Source="http://www.google.com" />
                    </TabItem.Content>
                </TabItem>

                <TabItem Header="Bing.com">
                    <TabItem.Content>
                        <WebBrowser Source="http://www.google.com" />
                    </TabItem.Content>
                </TabItem>

            </TabControl>
        </Grid>
    </Border>
</Window>

Screenshot:

No Transparency

The following code sets AllowsTransparency=True and WindowStyle=None:

<Window x:Class="AllowTransparencyIssue.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" 
        Height="500" 
        Width="700"
        AllowsTransparency="True"
        WindowStartupLocation="CenterScreen"
        WindowStyle="None"

        >
    <Border BorderBrush="Blue" BorderThickness="3">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition />
            </Grid.RowDefinitions>

            <Button Grid.Row="0" HorizontalAlignment="Right" Click="Button_Click">Close Window</Button>

            <TabControl Grid.Row="1">

                <TabItem Header="StartPage.com">
                    <TabItem.Content>
                        <WebBrowser Source="http://www.startpage.com" />
                    </TabItem.Content>
                </TabItem>

                <TabItem Header="Google.com">
                    <TabItem.Content>
                        <WebBrowser Source="http://www.google.com" />
                    </TabItem.Content>
                </TabItem>

                <TabItem Header="Bing.com">
                    <TabItem.Content>
                        <WebBrowser Source="http://www.google.com" />
                    </TabItem.Content>
                </TabItem>

            </TabControl>
        </Grid>
    </Border>
</Window>

Screenshot:

Allows Transparency

هل كانت مفيدة؟

المحلول

I found a post that appeared to be redundantly copied and pasted all over the web. The post helped me with my issue, but I decided to improve upon it and package it a bit cleaner. Also, the original code in the post didn't work when I used it in a TabControl.

Here is a link to the original post I found:

http://social.msdn.microsoft.com/Forums/en-US/41088e8f-800d-4a29-a693-d9edf1682c0f/c-wpf-winforms-web-browser-styling?forum=wpf

The solution above calls for creating a Window that hosts a Windows Forms WebBrowser Control in a WindowsFormsHost object that will essentially overlay itself on top of a border control.

Here is my improvement to the solution:

WebBrowserOverlayWindow.xaml:

<Window x:Class="AllowTransparencyIssue.WebBrowserOverlayWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="WebBrowserOverlayWindow"
        xmlns:winForms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"     
        WindowStyle="None"
        ShowInTaskbar="False"
        ResizeMode="NoResize">
    <WindowsFormsHost x:Name="wfh">
        <winForms:WebBrowser x:Name="wfBrowser" />
    </WindowsFormsHost>
</Window>

WebBrowserOverlayWindow.xaml.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace AllowTransparencyIssue
{
    /// <summary>
    /// Interaction logic for WebBrowserOverlayWindow.xaml
    /// </summary>
    public partial class WebBrowserOverlayWindow : Window
    {
        public WebBrowserOverlayWindow()
        {
            InitializeComponent();
        }

        public static readonly DependencyProperty TargetElementProperty = DependencyProperty.Register("TargetElement", typeof(FrameworkElement), typeof(WebBrowserOverlayWindow), new PropertyMetadata(TargetElementPropertyChanged));
        public FrameworkElement TargetElement
        {
            get
            {
                return GetValue(TargetElementProperty) as FrameworkElement;
            }
            set
            {
                SetValue(TargetElementProperty, value);
            }
        }


        public static readonly DependencyProperty SourceProperty = DependencyProperty.Register("Source", typeof(string), typeof(WebBrowserOverlayWindow), new PropertyMetadata(SourcePropertyChanged));
        public string Source
        {
            get
            {
                return GetValue(SourceProperty) as string;
            }
            set
            {
                SetValue(SourceProperty, value);
            }
        }
        private static void SourcePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            var webBrowserOverlayWindow = sender as WebBrowserOverlayWindow;

            if (webBrowserOverlayWindow != null)
            {
                webBrowserOverlayWindow.wfBrowser.Navigate(args.NewValue as string);
            }
        }

        private static void TargetElementPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            var oldTargetElement = args.OldValue as FrameworkElement;
            var webBrowserOverlayWindow = sender as WebBrowserOverlayWindow;
            var mainWindow = Window.GetWindow(webBrowserOverlayWindow.TargetElement);

            if (webBrowserOverlayWindow != null && mainWindow != null)
            {
                webBrowserOverlayWindow.Owner = mainWindow;
                webBrowserOverlayWindow.Owner.LocationChanged += webBrowserOverlayWindow.PositionAndResize;
                webBrowserOverlayWindow.TargetElement.LayoutUpdated += webBrowserOverlayWindow.PositionAndResize;

                if (oldTargetElement != null)
                    oldTargetElement.LayoutUpdated -= webBrowserOverlayWindow.PositionAndResize;

                webBrowserOverlayWindow.PositionAndResize(sender, new EventArgs());

                if (webBrowserOverlayWindow.TargetElement.IsVisible && webBrowserOverlayWindow.Owner.IsVisible)
                {
                    webBrowserOverlayWindow.Show();
                }

                webBrowserOverlayWindow.TargetElement.IsVisibleChanged += (x, y) =>
                {
                    if (webBrowserOverlayWindow.TargetElement.IsVisible && webBrowserOverlayWindow.Owner.IsVisible)
                    {
                        webBrowserOverlayWindow.Show();
                    }
                    else
                    {
                        webBrowserOverlayWindow.Hide();
                    }
                };
            }
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);

            Owner.LocationChanged -= PositionAndResize;
            if (TargetElement != null)
            {
                TargetElement.LayoutUpdated -= PositionAndResize;
            }
        }

        private void PositionAndResize(object sender, EventArgs e)
        {
            if (TargetElement != null && TargetElement.IsVisible)
            {
                var point = TargetElement.PointToScreen(new Point());
                Left = point.X;
                Top = point.Y;

                Height = TargetElement.ActualHeight;
                Width = TargetElement.ActualWidth;
            }
        }

    }
}

Generic.xaml ResourceDictionary (in the "Themes" folder):

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:AllowTransparencyIssue">


    <Style TargetType="{x:Type local:TransparentWebBrowser}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:TransparentWebBrowser}">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}">
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

TransparentWebBrowser.cs (Custom Control):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace AllowTransparencyIssue
{

    public class TransparentWebBrowser : Control
    {

        private WebBrowserOverlayWindow _WebBrowserOverlayWindow;
        public static readonly DependencyProperty TargetElementProperty = DependencyProperty.Register("TargetElement", typeof(FrameworkElement), typeof(TransparentWebBrowser), new PropertyMetadata(TargetElementPropertyChanged));
        public FrameworkElement TargetElement
        {
            get
            {
                return GetValue(TargetElementProperty) as FrameworkElement;
            }
            set
            {
                SetValue(TargetElementProperty, value);
            }
        }

        public static readonly DependencyProperty SourceProperty = DependencyProperty.Register("Source", typeof(string), typeof(TransparentWebBrowser), new PropertyMetadata(SourcePropertyChanged));
        public string Source
        {
            get
            {
                return GetValue(SourceProperty) as string;
            }
            set
            {
                SetValue(SourceProperty, value);
            }
        }

        private static void SourcePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            var transparentWebBrowser = sender as TransparentWebBrowser;
            if (transparentWebBrowser != null)
            {
                transparentWebBrowser._WebBrowserOverlayWindow.Source = args.NewValue as string;
            }
        }

        private static void TargetElementPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            var transparentWebBrowser = sender as TransparentWebBrowser;
            if (transparentWebBrowser != null)
            {
                transparentWebBrowser._WebBrowserOverlayWindow.TargetElement = args.NewValue as FrameworkElement;
            }
        }

        public TransparentWebBrowser()
        {
            _WebBrowserOverlayWindow = new WebBrowserOverlayWindow();

            //TODO: Figure out how to automatically set the TargetElement binding...

            //var targetElementBinding = new Binding();
            //var rs = new RelativeSource();
            //rs.AncestorType = typeof(Border);
            //targetElementBinding.RelativeSource = rs;

            //_WebBrowserOverlayWindow.SetBinding(TransparentWebBrowser.TargetElementProperty, targetElementBinding);


        }

        static TransparentWebBrowser()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(TransparentWebBrowser), new FrameworkPropertyMetadata(typeof(TransparentWebBrowser)));
        }
    }
}

Modified MainWindow.xaml:

<Window x:Class="AllowTransparencyIssue.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:AllowTransparencyIssue"
        Title="MainWindow" 
        Height="500" 
        Width="700"
        AllowsTransparency="True"
        WindowStartupLocation="CenterScreen"
        WindowStyle="None"


        >
    <Border BorderBrush="Blue" BorderThickness="3">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition />
            </Grid.RowDefinitions>

            <Button Grid.Row="0" HorizontalAlignment="Right" Click="Button_Click">Close Window</Button>

            <TabControl Grid.Row="1">

                <TabControl.Items>
                    <TabItem Header="StartPage.com">
                        <TabItem.Content>
                            <Border>
                                <local:TransparentWebBrowser TargetElement="{Binding RelativeSource={RelativeSource AncestorType={x:Type FrameworkElement}}}" Source="http://www.startpage.com" />
                            </Border>
                        </TabItem.Content>

                    </TabItem>

                    <TabItem Header="Google.com">
                        <TabItem.Content>
                            <Border>
                                <local:TransparentWebBrowser TargetElement="{Binding RelativeSource={RelativeSource AncestorType={x:Type FrameworkElement}}}" Source="http://www.google.com" />
                            </Border>
                        </TabItem.Content>
                    </TabItem>

                    <TabItem Header="Bing.com">
                        <TabItem.Content>
                            <Border>
                                <local:TransparentWebBrowser TargetElement="{Binding RelativeSource={RelativeSource AncestorType={x:Type FrameworkElement}}}" Source="http://www.bing.com" />
                            </Border>
                        </TabItem.Content>
                    </TabItem>

                </TabControl.Items>
            </TabControl>
        </Grid>
    </Border>
</Window>

Screenshot to prove this works: Final Screenshot

My final thought and question to my answer is, can anybody figure out how to wire-up the binding code in the instance constructor of the "TransparentWebBrowser" class so I don't have to explicitly set the TargetElement property in the MainWindow.xaml???

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top