Auf Englisch lesen

Freigeben über


INotifyPropertyChanged.PropertyChanged Ereignis

Definition

Tritt ein, wenn sich ein Eigenschaftswert ändert.

event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged;

Ereignistyp

Beispiele

Im folgenden Codebeispiel wird veranschaulicht, wie das PropertyChanged Ereignis der INotifyPropertyChanged Schnittstelle implementiert wird.

// This is a simple customer class that 
// implements the IPropertyChange interface.
public class DemoCustomer : INotifyPropertyChanged
{
    // These fields hold the values for the public properties.
    private Guid idValue = Guid.NewGuid();
    private string customerNameValue = string.Empty;
    private string phoneNumberValue = string.Empty;

    public event PropertyChangedEventHandler PropertyChanged;

    // This method is called by the Set accessor of each property.
    // The CallerMemberName attribute that is applied to the optional propertyName
    // parameter causes the property name of the caller to be substituted as an argument.
    private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    // The constructor is private to enforce the factory pattern.
    private DemoCustomer()
    {
        customerNameValue = "Customer";
        phoneNumberValue = "(312)555-0100";
    }

    // This is the public factory method.
    public static DemoCustomer CreateNewCustomer()
    {
        return new DemoCustomer();
    }

    // This property represents an ID, suitable
    // for use as a primary key in a database.
    public Guid ID
    {
        get
        {
            return this.idValue;
        }
    }

    public string CustomerName
    {
        get
        {
            return this.customerNameValue;
        }

        set
        {
            if (value != this.customerNameValue)
            {
                this.customerNameValue = value;
                NotifyPropertyChanged();
            }
        }
    }

    public string PhoneNumber
    {
        get
        {
            return this.phoneNumberValue;
        }

        set
        {
            if (value != this.phoneNumberValue)
            {
                this.phoneNumberValue = value;
                NotifyPropertyChanged();
            }
        }
    }
}

Hinweise

Das PropertyChanged -Ereignis kann angeben, dass alle Eigenschaften des -Objekts geändert wurden, indem entweder null oder String.Empty als Eigenschaftsname in verwendet PropertyChangedEventArgswird. Beachten Sie, String.Empty dass in einer UWP-Anwendung anstelle nullvon verwendet werden muss.

Gilt für:

Weitere Informationen