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 は、DependencyObject のバインド機能を公開するために使用されます。

基本的に、DependencyObject から派生していないクラスで DependencyProperty を宣言することはできません。また、そのオブジェクトの DataContext のプロパティにバインドされる DependencyObject で使用されていない限り、DependencyProperty を宣言する必要はありません。

于 2013-03-20T16:20:56.777 に答える