简体   繁体   中英

How can I use a dotted path as a property name of a PropertyChangedEventHandler?

How can I use a dotted path as a property name of a PropertyChangedEventHandler?

public class Person
{
    private int _age;
    public int Age
    {
        get { return _age;}
        set
        {
            _age = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

public partial class MyControl : UserControl, INotifyPropertyChanged
{
    public Person Person
    {
        get { return (Person)GetValue(PersonProperty); }
        set { SetValue(PersonProperty, value); }
    }

    public static DependencyProperty PersonProperty =
        DependencyProperty.Register("Person", typeof (Person), typeof (MyControl), null);

    private void someMethod()
    {
        OnPropertyChanged("Person.Age");
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); 
    }   
}

<TextBox Text="{Binding Person.Age, Mode=TwoWay}"/>

But OnPropertyChanged("Person.Age") cannot resolve the symbol.

Is it possible to use a dotted path as a propertyName of OnPropertyChanged()?

The Age setter, you should always call OnPropertyChanged("Age") .

INotifyPropertyChanged isn't meant to be used for sub-properties. You also don't need it on a UserControl, since dependency properties already provide notification. Once you fix your OnPropertyChanged call in the Person class you should be fine.

You have a couple of options to fix the Person.Age setter:

  1. Call OnPropertyChanged("Age") (and remove the = null in the OnPropertyChanged signature.

  2. If you are targeting .NET 4.5 or later, the preferred solution is to change the Person.OnPropertyChanged signature to be OnPropertyChanged(string [CallerMemberName] propertyName = null) . Calling OnPropertyChanged() from the Age setter will then fill set propertyName to Age . See the this blog post or the MSDN documentation for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM