WPF WebBrowser Control Custom Property

2019-09-05 16:35发布

Ok. So I ran across a couple code examples stating that I can create a custom property for the WPF WebBrowser control, that will allow me to bind a string of html to the control for rendering.

Here is the class for the property (which is in a file called BrowserHtmlBinding.vb):

Public Class BrowserHtmlBinding

Private Sub New()
End Sub

Public Shared BindableSourceProperty As DependencyProperty =
    DependencyProperty.RegisterAttached("Html",
                                        GetType(String),
                                        GetType(WebBrowser),
                                        New UIPropertyMetadata(Nothing,
                                                                AddressOf BindableSourcePropertyChanged))

Public Shared Function GetBindableSource(obj As DependencyObject) As String
    Return DirectCast(obj.GetValue(BindableSourceProperty), String)
End Function

Public Shared Sub SetBindableSource(obj As DependencyObject, value As String)
    obj.SetValue(BindableSourceProperty, value)
End Sub

Public Shared Sub BindableSourcePropertyChanged(o As DependencyObject, e As DependencyPropertyChangedEventArgs)
    Dim webBrowser = DirectCast(o, System.Windows.Controls.WebBrowser)
    webBrowser.NavigateToString(DirectCast(e.NewValue, String))
End Sub

End Class

And the Xaml:

<Window x:Class="Details"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:custom="clr-namespace:BrowserHtmlBinding"
Title="Task Details" Height="400" Width="800" Icon="/v2Desktop;component/icon.ico"
WindowStartupLocation="CenterScreen" WindowStyle="ThreeDBorderWindow"
WindowState="Maximized">
    <Grid>
        <WebBrowser custom:Html="&lt;b&gt;Hey Now&lt;/b&gt;" />
    </Grid>
</Window>

I keep getting an error: Error 1 The property 'Html' was not found in type 'WebBrowser'.

How do I fix this??? It's driving me up a wall!

1条回答
放荡不羁爱自由
2楼-- · 2019-09-05 17:02

You're listing the class name as the namespace in your xmlns mapping and then you're not listing the class name in the actual attached property usage. I can't tell from your snippet what you're namespace is (you can check the Project properties to find the Root namespace) but assuming its something like WpfApplication1, the xaml would look like the following.

<Window x:Class="Details" 
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
  xmlns:custom="clr-namespace:WpfApplication1" 
  Title="Task Details" Height="400" Width="800" 
  Icon="/v2Desktop;component/icon.ico" WindowStartupLocation="CenterScreen"
  WindowStyle="ThreeDBorderWindow" WindowState="Maximized"> 
<Grid> 
    <WebBrowser custom:BrowserHtmlBinding.Html="&lt;b&gt;Hey Now&lt;/b&gt;" /> 
</Grid> 

查看更多
登录 后发表回答