WPF: Can't binding to Dependency Property in User Control

余生颓废 提交于 2019-12-12 03:34:34

问题


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}


来源:https://stackoverflow.com/questions/15086569/wpf-cant-binding-to-dependency-property-in-user-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!