1

我的属性描述中有一个 html。当我将此属性与文本块(例如 texthide)绑定时,它会在文本块中显示 html。但我无法将 WebBrowser 与此属性绑定。如何将 html 字符串绑定到 WebBrowser?

<ScrollViewer 
  HorizontalScrollBarVisibility="Disabled" 
  VerticalScrollBarVisibility="Auto" 
  Margin="25, 0, 0, 0" 
  Grid.Row="0">

  <StackPanel Orientation="Vertical">

    <TextBlock 
      x:Name="TextHide"  
      Text="{Binding Path=Descrption}" 
      Style="{StaticResource servicesText}" 
      TextWrapping="Wrap" />
    <phone:WebBrowser 
      Source="{Binding Descrption}" 
      x:Name="webBrowserHTML" 
      Foreground="Black" 
      Loaded="webBrowserHTML_Loaded" />

<!--<Image Source="../Images/cont_banner.png" Width="270"  Grid.Row="1"/>-->

    <Button Grid.Row="1">
      <Button.Background>
        <ImageBrush ImageSource="../Images/cont_banner.png" />
      </Button.Background>
      <Button.Content>
        <HyperlinkButton Content="" NavigateUri="callto:3950" />
      </Button.Content>
    </Button>

  </StackPanel>

</ScrollViewer>

请问有什么想法吗?此致

4

1 回答 1

5

为了能够将 HTML 直接绑定到WebBrowser控件,您必须创建一个附加属性:

namespace YourAppNamespace
{
    public static class WebBrowserHelper
    {
        public static readonly DependencyProperty HtmlProperty = DependencyProperty.RegisterAttached(
            "Html", typeof(string), typeof(WebBrowserHelper), new PropertyMetadata(OnHtmlChanged));

        public static string GetHtml(DependencyObject dependencyObject)
        {
            return (string)dependencyObject.GetValue(HtmlProperty);
        }

        public static void SetHtml(DependencyObject dependencyObject, string value)
        {
            dependencyObject.SetValue(HtmlProperty, value);
        }

        private static void OnHtmlChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var browser = d as WebBrowser;

            if (browser == null)
                return;

            var html = e.NewValue.ToString();

            browser.NavigateToString(html);
        }
    }
}

添加所需的 XAML 命名空间声明:

xmlns:cxi="clr-namespace:YourAppNamespace"

并像这样使用它:

<phone:WebBrowser cxi:WebBrowserHelper.Html="{Binding Question.Body}" />

资源

于 2012-11-23T20:53:18.627 回答