使用C#中的WebBrowser进行用户控制

时间:2013-12-05 12:54:52

标签: c# wpf user-controls

我正在使用WebBrowser和一个依赖项属性编写用户控件。 在Text中更改之后我想刷新浏览器输出。

 public class BrowserControl : Control
 {
     //....
    public static readonly DependencyProperty ContentProperty =
       DependencyProperty.Register("Text", typeof(object), typeof(BrowserControl), new UIPropertyMetadata(null));

    public String Text
    {
        get { return (String)GetValue(ContentProperty); }
        set {   SetValue(ContentProperty, value);
                br = new WebBrowser();
                br.NavigateToString(value);
            }
    }

    private WebBrowser br;
    public WebBrowser Browser { get; set; }
}

我已将此控件放在wpf应用程序中,但是没有来自控件的输出。我认为我必须修改控件模板。 常规模板如下所示:

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BrowserControl">
<Style TargetType="{x:Type local:BrowserControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:BrowserControl}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                </Border>                    
            </ControlTemplate>
         </Setter.Value>
    </Setter>
</Style>
</ResourceDictionary>

我是新手,不知道如何将webbrowser作为整个控件的可见元素?

此外,我想知道如何在WPF应用程序中使用Binding与TextBox和BrowserControl的Text属性。 我想做某事:

<TextBox ... Text="{Binding Path=browserCtrl.Text}" ...>

因此,当TextBox中的文本发生更改时,我的自定义控件将在浏览器中重新呈现该网站。

2 个答案:

答案 0 :(得分:1)

我认为这可能对你有帮助....

只需输入网址和标签即可。

<强> BrowserControl.cs

public class BrowserControl : Control
    {
        public static readonly DependencyProperty URLproperty
            = DependencyProperty.Register(
                "URL",
                typeof (string),
                typeof (BrowserControl),
                new PropertyMetadata(string.Empty, OnURLPropertyChanged),
                OnValidateURLCallBack);

        private static bool OnValidateURLCallBack(object value)
        {
            Uri uri = null;
            var url = Convert.ToString(value);
            if (!string.IsNullOrEmpty(url))
            {
                return Uri.TryCreate(Convert.ToString(value), UriKind.Absolute, out uri);
            }
            return true;
        }

        private static void OnURLPropertyChanged(object sender, DependencyPropertyChangedEventArgs args)
        {
            var browserControl = sender as BrowserControl;
            if (browserControl != null)
            {
                Uri uri = null;
                var url = Convert.ToString(args.NewValue);
                var template = browserControl.Template;
                if (template != null)
                {
                    var internalBrowser =
                        browserControl.Template.FindName("_InternalBrowser", browserControl) as WebBrowser;
                    if (internalBrowser != null)
                    {
                        if (!string.IsNullOrEmpty(url) && Uri.TryCreate(url, UriKind.Absolute, out uri))
                        {
                            internalBrowser.Navigate(uri);
                        }
                        else if (string.IsNullOrEmpty(url))
                        {
                            internalBrowser.NavigateToStream(new MemoryStream(Encoding.ASCII.GetBytes(string.Empty)));
                        }
                    }
                }
            }
        }

        public string URL
        {
            get { return Convert.ToString(GetValue(URLproperty)); }
            set { SetValue(URLproperty, value); }
        }
    }

<强> Generic.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:WpfApplication1">
    <Style TargetType="{x:Type local:BrowserControl}" x:Key="{x:Type local:BrowserControl}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:BrowserControl}">
                    <Border Background="{TemplateBinding Background}"
                    BorderBrush="{TemplateBinding BorderBrush}"
                    BorderThickness="{TemplateBinding BorderThickness}">
                        <WebBrowser x:Name="_InternalBrowser"/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

<强> MainWindow.xaml

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="BrowserHost" Height="350" Width="525">
  <Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Generic.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
  </Window.Resources>
  <Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <DockPanel Margin="2">
        <TextBlock FontWeight="Bold" Text="URL: " Margin="1" DockPanel.Dock="Left"/>
        <TextBox Text="{Binding ElementName=MyBrowserControl, Path=URL, Mode=TwoWay}" DockPanel.Dock="Right"/>
    </DockPanel>
    <local:BrowserControl x:Name="MyBrowserControl" Grid.Row="1" BorderBrush="Blue" BorderThickness="1">
    </local:BrowserControl>
  </Grid>
 </Window>

答案 1 :(得分:0)

您可能会发现使用UserControl类更容易...只需在WebBrowser XAML中添加UserControl控件,然后将DependencyProperty添加到后面的代码中:

<UserControl x:Class="WpfApplication1.Views.WebBrowserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    mc:Ignorable="d" 
    d:DesignHeight="300" d:DesignWidth="300">
    <WebBrowser Name="WebBrowser" /><!--Declare this here, not in code behind-->
</UserControl>

对于第二项要求,您应该调查WebBrowser.WebBrowser.Navigate和/或WebBrowser.NavigateToString方法。

最后,为了对DependencyProperty中的更改做出反应,您需要添加PropertyChangedCallback处理程序。您可以通过查看MSDN上的Dependency Property Callbacks and Validation页面了解如何执行此操作。