Search code examples
wpfuser-controlsinotifypropertychanged

Custom object as a DependencyProperty


I have a custom class, MyPerson. All (relevant) properties implement INotifyPropertyChanged. I created a UserControl to display it, and it all worked fine. Binding to properties like MyPerson.FirstName (a string) all work - they display and update (two way binding) as expected.

Now I want to do more complex stuff in the codebehind, so I wanted to create a DependencyProperty with a PropertyType of MyPerson, but I'm not sure how to construct the DependencyProperty, in particular the PropertyChangedCallback part.

Can this be done? How so?


Solution

  • Read on this article - Custom Dependency Properties

    Something like -

    public static readonly DependencyProperty MyPersonValueProperty = 
          DependencyProperty.Register( "MyPersonValue", typeof(MyPerson), 
             typeof(MyPersonControl), new FrameworkPropertyMetadata(null, 
                 FrameworkPropertyMetadataOptions.AffectsRender,
                   new PropertyChangedCallback(OnPersonChanged) ) ); 
    
    public MyPerson ThePerson
    { 
        get { return (MyPerson)GetValue(MyPersonValueProperty); }
        set { SetValue(MyPersonValueProperty, value); }
    }
    
    private static void OnPersonChanged(DependencyObject d, 
                                     DependencyPropertyChangedEventArgs e)
    {
        // Property change code here
    }