WPF: Can't binding to Dependency Property in U

2019-09-17 20:26发布

问题:

Why I can't bind to the Dependency Property in my UserControl? I only see the String "Test" as the default value but the binding does not run in a test application. if i do the same binding in the test application in a textblock object than it works. so the problem must be in the myItem class with the dependencyproperty.

Code:

public partial class myItem : UserControl, INotifyPropertyChanged
{
    public static DependencyProperty HeaderProperty =
            DependencyProperty.Register("Header", typeof(String), typeof(myItem), new UIPropertyMetadata("Test"));

    public myItem()
    {
        InitializeComponent();
        DataContext = this;
    }

    public String Header
    {
        get
        {
            return (String)GetValue(HeaderProperty);
        }
        set
        {
            SetValue(HeaderProperty, value);
            OnPropertyChanged("Header");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

回答1:

The dependency property already handles notifying of changes so you don't explicitly have to implement INotifyPropertyChanged. So you can remove the OnPropertyChanged("Header"); from the setter

If you wanted to call a function on the change of this property the correct way is to define it in the Dependency property:

 public static DependencyProperty HeaderProperty =
            DependencyProperty.Register("Header", typeof(String), typeof(myItem), new PropertyMetadata("Test", OnHeaderChanged));

    public String Header
        {
            get
            {
                return (String)GetValue(HeaderProperty);
            }
            set
            {
                SetValue(HeaderProperty, value);
            }
        }

    private void OnHeaderChanged(DependencyObject d, DependencyPropertyChangedEventArgs e){ //do something}