0

如何添加自定义 DependencyProperty?这种方法不起作用。

public class SongCollection : ObservableCollection<Song>
{
public static readonly DependencyProperty UrlProperty = DependencyProperty.Register(
  "Url", typeof(ObservableCollection<Point>), typeof(Arrow));
public Uri Url
        {
            get { return (Uri)GetValue(UrlProperty);}
            ....
        }
}
4

2 回答 2

1

那么问题应该是它不编译。由于ObservableCollection<T> 不是从 派生DependencyObject,因此即使我会更正其余代码,此实现也无法工作,这也是完全错误的。

有关更多信息,DependencyProperties请查看此处

编辑

您的财产的正确实施将是

public class SomeClass : DependencyObject
{
    public static readonly DependencyProperty UrlProperty = 
        DependencyProperty.Register("Url", typeof(Uri), typeof(SomeClass));

    public Uri Url
    {
        get { return (Uri)GetValue(UrlProperty);}
        set { SetValue(UrlProperty, value); }
    }
}

编辑 2

包装器实现

public class SomeClass : DependencyObject
{
    public static readonly DependencyProperty UrlProperty = 
        DependencyProperty.Register("Url", typeof(Uri), typeof(SomeClass), 
        new PropertyMeta(OnUrlChanged));

    public Uri Url
    {
        get { return (Uri)GetValue(UrlProperty);}
        set { SetValue(UrlProperty, value); }
    }

    public ObservableCollection<Song> Songs { get; set; }

    private static void OnUrlChanged (DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var wrapper = d as SomeClass;
        if (wrapper == null)
            return;

        // ... what ever you want to do with the collection
    }
}
于 2013-03-20T15:54:48.543 回答
0

DependencyProperties 用于在 DependencyObjects 上公开绑定功能。

基本上,您不能在不是从 DependencyObject 派生的类上声明 DependencyProperty,而且,除非在 DependencyObject 上使用它以绑定到该对象的 DataContext 中的属性,否则您不需要声明 DependencyProperty。

于 2013-03-20T16:20:56.777 回答