我在看this question,但我不明白如何實際使用創建的AttachedProperty。問題是試圖對WebBrowser控件的源進行綁定。使用自定義附加屬性和綁定
的代碼有看起來像:
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 = uri != null ? new Uri(uri) : null;
}
}
}
和
<WebBrowser ns:WebBrowserUtility.BindableSource="{Binding WebAddress}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Disabled"
Width="300"
Height="200" />
的WebAddress,那是什麼呢?這是我的理解(這可能是錯誤的):
- 有可連接到任何物體的AttachedProperty,在這種特殊情況下,它基本上只是附加了一個名爲BindableSource屬性,它是String類型。
當我們擁有了「{結合WebAddress}」這意味着,在一些C#代碼的地方,處理此的.xaml文件裏面的東西,看起來像:
public String WebAddress { // get and set here? not sure }
- 和屬性改爲利用,我可以調用RaisedPropertyChanged,它會在那裏觸發靜態方法?
即使我看着它,它似乎並不正確,但我無法找到任何在線幫助我。
實際上,OP可能*不希望在實現WebAddress屬性的ViewModel類中引發PropertyChanged事件 – cordialgerm
@pickles:嗯,這聽起來很合理。 –
@pickles:我明顯更新了我的答案,希望能夠解決所有問題。 –