数据绑定 WPF 中 WebBrowser 的 Source 属性 [英] databind the Source property of the WebBrowser in WPF
问题描述
有谁知道如何在 WPF ( 3.5SP1 ) 中对 WebBrowser 的 .Source 属性进行数据绑定?我有一个列表视图,我希望左侧有一个小的 WebBrowser,右侧有一个内容,并将每个 WebBrowser 的源与绑定到列表项的每个对象中的 URI 进行数据绑定.
Does anyone know how to databind the .Source property of the WebBrowser in WPF ( 3.5SP1 )? I have a listview that I want to have a small WebBrowser on the left, and content on the right, and to databind the source of each WebBrowser with the URI in each object bound to the list item.
到目前为止,这是我作为概念证明的内容,但是<WebBrowser Source="{Binding Path=WebAddress}"
"无法编译.
This is what I have as a proof of concept so far, but the "<WebBrowser Source="{Binding Path=WebAddress}"
" does not compile.
<DataTemplate x:Key="dealerLocatorLayout" DataType="DealerLocatorAddress">
<StackPanel Orientation="Horizontal">
<!--Web Control Here-->
<WebBrowser Source="{Binding Path=WebAddress}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Disabled"
Width="300"
Height="200"
/>
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Path=CompanyName}" FontWeight="Bold" Foreground="Blue" />
<TextBox Text="{Binding Path=DisplayName}" FontWeight="Bold" />
</StackPanel>
<TextBox Text="{Binding Path=Street[0]}" />
<TextBox Text="{Binding Path=Street[1]}" />
<TextBox Text="{Binding Path=PhoneNumber}"/>
<TextBox Text="{Binding Path=FaxNumber}"/>
<TextBox Text="{Binding Path=Email}"/>
<TextBox Text="{Binding Path=WebAddress}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
推荐答案
问题在于 WebBrowser.Source
不是 DependencyProperty
.一种解决方法是使用一些 AttachedProperty
魔法来启用此功能.
The problem is that WebBrowser.Source
is not a DependencyProperty
. One workaround would be to use some AttachedProperty
magic to enable this ability.
public static class WebBrowserUtility
{
public static readonly DependencyProperty BindableSourceProperty =
DependencyProperty.RegisterAttached("BindableSource", typeof(string), typeof(WebBrowserUtility), new UIPropertyMetadata(null, BindableSourcePropertyChanged));
public static string GetBindableSource(DependencyObject obj)
{
return (string) obj.GetValue(BindableSourceProperty);
}
public static void SetBindableSource(DependencyObject obj, string value)
{
obj.SetValue(BindableSourceProperty, value);
}
public static void BindableSourcePropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
WebBrowser browser = o as WebBrowser;
if (browser != null)
{
string uri = e.NewValue as string;
browser.Source = !String.IsNullOrEmpty(uri) ? new Uri(uri) : null;
}
}
}
然后在您的 xaml 中执行:
Then in your xaml do:
<WebBrowser ns:WebBrowserUtility.BindableSource="{Binding WebAddress}"/>
这篇关于数据绑定 WPF 中 WebBrowser 的 Source 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!