WPF WebBrowser控件自定义属性

时间:2012-07-12 15:48:18

标签: .net wpf vb.net wpf-controls vb.net-2010

确定。所以我遇到了几个代码示例,说明我可以为WPF WebBrowser控件创建一个自定义属性,这将允许我将一个html字符串绑定到控件进行渲染。

这是属性的类(在名为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

和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>

我一直收到错误:错误1在'WebBrowser'类型中找不到属性'Html'。

我该如何解决这个问题?它让我爬上了墙!

1 个答案:

答案 0 :(得分:2)

您在xmlns映射中列出了名称作为名称空间,然后您没有在实际的附加属性用法中列出类名。我无法从你的代码片段中判断出你的命名空间是什么(你可以检查Project属性以找到Root命名空间)但是假设它类似 WpfApplication1 ,xaml将如下所示。< / p>

<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>