使用带有绑定的自定义附加属性

时间:2011-06-17 23:05:59

标签: c# wpf data-binding browser webbrowser-control

我在看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。
  • 当我们拥有“{Binding WebAddress}”时,这意味着在某些处理此.xaml文件的c#代码中,有一些看起来像:

    public String WebAddress
    { 
        // get and set here? not sure
    }
    
  • 为了利用更改的属性,我可以调用RaisedPropertyChanged并在那里触发那个静态方法?

即使我看着它,它似乎也不对,但我找不到任何在线帮助我。

1 个答案:

答案 0 :(得分:2)

  

可以附加到任何对象的AttachedProperty,在这种特殊情况下,它基本上只附加一个名为BindableSource的属性,类型为String。

您可能需要阅读MSDN article on attached properties

这很简单:Dependency properties使用字典,其中控件与属性的值相关联,这使得添加类似附加属性的内容变得非常容易,这可以扩展控件。

在附加属性的RegisterAttached方法中,连接了PropertyChangedCallback,如果值发生变化,将执行该WebAddress。使用依赖项属性可以启用绑定,这是首先要做的事情。如果值发生变化,所有属性都会调用相关代码来浏览浏览器。


  

当我们拥有“{Binding WebAddress}”时,这意味着在某些处理此.xaml文件的c#代码中,有些东西看起来像[...]

绑定在WebBrowser的property内引用了一些名为public class MyModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } private string _webAddress; public string WebAddress { get { return _webAddress; } set { if (value != _webAddress) { _webAddress = value; NotifyPropertyChanged("WebAddress"); } } } } 的公共field或依赖属性( not a DataContext)。有关数据绑定的一般信息,请参阅Data Binding Overview

因此,如果你想创建一个应该是绑定源的属性,你要么实现INotifyPropertyChanged,要么创建一个DependencyProperty(它们自己发出更改通知,你通常只在控件和UI上创建它们 - 相关课程)

您的财产可能如下所示:

PropertyChanged

在这里你必须像你怀疑的那样在setter中引发PropertyChangedCallback事件。如何在XAML中实际声明工作绑定是一个相当广泛的主题,我想再次引导您前面提到的Data Binding Overview,这应该解释一下。


  

为了利用更改的属性,我可以调用RaisedPropertyChanged并在那里触发那个静态方法?

触发事件以触发绑定更新,这反过来会更改附加属性的值,从而导致{{1}}执行,最终导航浏览器。