• Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Raise an event whenever a property's value changed?

There is a property, it's named ImageFullPath1

I'm going fire an event whenever its value changed. I am aware of changing INotifyPropertyChanged , but I want to do it with events.

wonea's user avatar

6 Answers 6

The INotifyPropertyChanged interface is implemented with events. The interface has just one member, PropertyChanged , which is an event that consumers can subscribe to.

The version that Richard posted is not safe. Here is how to safely implement this interface:

Note that this does the following things:

Abstracts the property-change notification methods so you can easily apply this to other properties;

Makes a copy of the PropertyChanged delegate before attempting to invoke it (failing to do this will create a race condition).

Correctly implements the INotifyPropertyChanged interface.

If you want to additionally create a notification for a specific property being changed, you can add the following code:

Then add the line OnImageFullPathChanged(EventArgs.Empty) after the line OnPropertyChanged("ImageFullPath") .

Since we have .Net 4.5 there exists the CallerMemberAttribute , which allows to get rid of the hard-coded string for the property name in the source code:

Oliver's user avatar

  • 29 +1 for being the only person in this thread so far to get the null check on the event correct. –  Simon P Stevens Feb 11, 2010 at 18:55
  • @Aaronaught: How to wire up the event-method with event?could you please explain.. I mean, where do I need to write the implementation for the event? –  techBeginner Oct 26, 2011 at 18:33
  • Why use the local var "handler", why not just if (ImageFullPathChanged != null) ImageFullPathChanged(this, e); –  dlchambers Jul 14, 2015 at 14:03
  • 1 since the compiler will process lvalues before rvalues ImageFullPathChanged?.Invoke... will always negate the race condition, i.e. ImageFullPathChanged will never be invoked if it is null. Its just syntactic sugar which Roslyn would then process on build. would need to check IL output to verify but pretty certain. –  Lou Watson Oct 11, 2016 at 1:06
  • 5 I would replace the parameter from call of OnPropertyChanged("ImageFullPath"); with nameof(ImageFullPath) . This way you will have compile time checking of the name of the property so in case you will ever change it, you will receive an error message if you forget to replace it in the method call too. –  meJustAndrew Mar 2, 2018 at 13:08

I use largely the same patterns as Aaronaught, but if you have a lot of properties it could be nice to use a little generic method magic to make your code a little more DRY

Usually I also make the OnPropertyChanged method virtual to allow sub-classes to override it to catch property changes.

Mikael Sundberg's user avatar

  • 12 Now with .NET 4.5 you can even get the property name for free using the CallerMemberNameAttribute msdn.microsoft.com/en-us/library/… . –  fsimonazzi Oct 25, 2012 at 17:40
  • This is working great. Thanks for the example. +1 for the CallerMemberName –  curob Aug 31, 2016 at 16:43
  • 1 Time went since last edit and some things changed. Maybe better way to invoke event delegate: PropertyChanged?.Invoke(this, e); –  Tzwenni Sep 2, 2020 at 9:24

Raising an event when a property changes is precisely what INotifyPropertyChanged does. There's one required member to implement INotifyPropertyChanged and that is the PropertyChanged event. Anything you implemented yourself would probably be identical to that implementation, so there's no advantage to not using it.

Ryan Brunner's user avatar

  • 2 +1 for truth. Even if you want to implement a separate XChangedEvent for every property, you're already doing the work, so go ahead and implement INotifyPropertyChanged too. The future (like WPF) will thank you, because that's what the future expects you to do. –  Greg D Feb 11, 2010 at 18:48

That said, I completely agree with Ryan. This scenario is precisely why INotifyPropertyChanged exists.

Richard Berg's user avatar

  • 3 This event invocation has a race condition. The value of ImageFullPath1Changed can change to null between the check and the subsequent invocation. Do not invoke events like this! –  Aaronaught Feb 11, 2010 at 18:52
  • 2 Your check for null of the ImageFullPath1Changed event is not safe. Given that events can be subscribed/unsubscribed to/from asynchronously from outside of your class, it could become null after your null check and cause a NullReferenceException. Instead, you should take a local copy before checking for null. See Aaronaught's answer. –  Simon P Stevens Feb 11, 2010 at 18:54

If you change your property to use a backing field (instead of an automatic property), you can do the following:

Oded's user avatar

  • Your check for null of the ImageFullPath1Changed event is not safe. Given that events can be subscribed/unsubscribed to/from asynchronously from outside of your class, it could become null after your null check and cause a NullReferenceException. Instead, you should take a local copy before checking for null. See Aaronaught's answer –  Simon P Stevens Feb 11, 2010 at 18:54
  • 1 @Simon P Stevens - thanks for the info. Updated answer to reflect. –  Oded Feb 11, 2010 at 19:12
  • @Oded I tried using your approach, but for the above code handler(this, e), e does not exist in current context Am I mssing something? –  Abhijeet Nov 10, 2012 at 5:59
  • 1 @autrevo - The e is simply an example. You need to pass in an instance of EventArgs . If you don't have any to pass, you can use EventArgs.Empty . –  Oded Nov 10, 2012 at 8:09
  • @Simon P Stevens I prerfer using. public event EventHandler ImageFullPath1Changed = delegate {}; Then avoid having to check for null.... –  madrang Mar 20, 2014 at 5:47

There is already have good answers but some people are still confused

  • EventArgs and who they can use it
  • And some of them about how to pass custom parameters

Jameel Nazir's user avatar

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct .

Not the answer you're looking for? Browse other questions tagged c# .net events properties or ask your own question .

  • The Overflow Blog
  • If you want to address tech debt, quantify it first
  • Fighting comment spam at Facebook scale (Ep. 602)
  • Featured on Meta
  • Moderation strike: Results of negotiations
  • Our Design Vision for Stack Overflow and the Stack Exchange network
  • Call for volunteer reviewers for an updated search experience: OverflowAI Search
  • Temporary policy: Generative AI (e.g., ChatGPT) is banned
  • Discussions experiment launching on NLP Collective

Hot Network Questions

  • How do strong (GM level) players visualise the board?
  • What would happen if the Panama Isthmus was turned into an island chain?
  • Best-Practice in word-embeddings
  • std::chrono compatible clock using CLOCK_MONOTONIC_RAW
  • What's the main difference between "You are not to use the elevator." and "You don't have to use the elevator"?
  • Refinishing particle board with vinyl veneer
  • How can drawing this cone always show code running?
  • Forward definition of measurability
  • Why are stars made from hydrogen and helium and not other elements?
  • Why did JavaScript choose to include a void operator?
  • I've always learned that data standardization is not necessary for OLS regression, but then recommended for neural networks. Intuitively, why is that?
  • How many days did it take for the Terminator to find real Sarah Connor?
  • Was there a German embassy open in 1941 Lisbon?
  • ZX Spectrum+ 48K with faulty memory writing address
  • Imbler v. Pachtman and Texas prosecutor Ken Anderson
  • Missing conjunction for multiple Organizations in BibLaTex APA style
  • How did Catwoman manage to pierce Batman's armor using a sewing claw?
  • What - - - - - - - corresponds to the question mark?
  • Are high-starch potatoes hard (low-starch soft)?
  • Is it safe to create a public ID by hashing a private key?
  • Unexpected poor performance with NVMe drives on an X9DR3-F
  • Ask for a reduction in conference registration fees
  • Migrating Windows to a new internal drive, changing drive letters?
  • How to fix UnicodeDecodeError?

property change event

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

How to: Implement Property Change Notification

  • 1 contributor

To support OneWay or TwoWay binding to enable your binding target properties to automatically reflect the dynamic changes of the binding source (for example, to have the preview pane updated automatically when the user edits a form), your class needs to provide the proper property changed notifications. This example shows how to create a class that implements INotifyPropertyChanged .

To implement INotifyPropertyChanged you need to declare the PropertyChanged event and create the OnPropertyChanged method. Then for each property you want change notifications for, you call OnPropertyChanged whenever the property is updated.

To see an example of how the Person class can be used to support TwoWay binding, see Control When the TextBox Text Updates the Source .

  • Binding Sources Overview
  • Data Binding Overview
  • How-to Topics

Submit and view feedback for

Additional resources

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

HTMLElement: change event

The change event is fired for <input> , <select> , and <textarea> elements when the user modifies the element's value. Unlike the input event, the change event is not necessarily fired for each alteration to an element's value .

Depending on the kind of element being changed and the way the user interacts with the element, the change event fires at a different moment:

  • When a <input type="checkbox"> element is checked or unchecked (by clicking or using the keyboard);
  • When a <input type="radio"> element is checked (but not when unchecked);
  • When the user commits the change explicitly (e.g., by selecting a value from a <select> 's dropdown with a mouse click, by selecting a date from a date picker for <input type="date"> , by selecting a file in the file picker for <input type="file"> , etc.);
  • When the element loses focus after its value was changed: for elements where the user's interaction is typing rather than selection, such as a <textarea> or the text , search , url , tel , email , or password types of the <input> element.

The HTML specification lists the <input> types that should fire the change event .

Use the event name in methods like addEventListener() , or set an event handler property.

A generic Event .

<select> element

Text input element.

For some elements, including <input type="text"> , the change event doesn't fire until the control loses focus. Try entering something into the field below, and then click somewhere else to trigger the event.

Specifications

Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

Different browsers do not always agree whether a change event should be fired for certain types of interaction. For example, keyboard navigation in <select> elements used to never fire a change event in Gecko until the user hit Enter or switched the focus away from the <select> (see Firefox bug 126379 ). Since Firefox 63 (Quantum), this behavior is consistent between all major browsers, however.

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases. See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

How to Write a Property Change Listener

Property-change events occur whenever the value of a bound property changes for a bean — a component that conforms to the JavaBeans™ specification. You can find out more about beans from the JavaBeans trail of the Java Tutorial. All Swing components are also beans.

A JavaBeans property is accessed through its get and set methods. For example, JComponent has the property font which is accessible through the getFont and setFont methods.

Besides the get and set methods, a bound property fires a property-change event when its value changes. For more information, see the Bound Properties page in the JavaBeans trail.

Some scenarios that commonly require property-change listeners include:

  • You have implemented a formatted text field and need a way to detect when the user has entered a new value. You can register a property-change listener on the formatted text field to listen to changes on the value property. See FormattedTextFieldDemo in How to Use Formatted Text Fields for an example of this.
  • You have implemented a dialog and need to know when a user has clicked one of the dialog's buttons or changed a selection in the dialog. See DialogDemo in How to Make Dialogs for an example of registering a property-change listener on an option pane to listen to changes to the value property. You can also check out FileChooserDemo2 in How to Use File Choosers for an example of how to register a property-change listener to listen to changes to the directoryChanged and selectedFileChanged properties.
  • You need to be notified when the component that has the focus changes. You can register a property-change listener on the keyboard focus manager to listen to changes to the focusOwner property. See TrackFocusDemo and DragPictureDemo in How to Use the Focus Subsystem for examples of this.

Although these are some of the more common uses for property-change listeners, you can register a property-change listener on the bound property of any component that conforms to the JavaBeans specification.

You can register a property change listener in two ways. The first uses the method addPropertyChangeListener(PropertyChangeListener) . When you register a listener this way, you are notified of every change to every bound property for that object. In the propertyChange method, you can get the name of the property that has changed using the PropertyChangeEvent getPropertyName method, as in the following code snippet:

The second way to register a property change listener uses the method addPropertyChangeListener(String, PropertyChangeListener) . The String argument is the name of a property. Using this method means that you only receive notification when a change occurs to that particular property. So, for example, if you registered a property change listener like this:

FontListener only receives notification when the value of the component's font property changes. It does not receive notification when the value changes for transferHandler , opaque , border , or any other property.

The following example shows how to register a property change listener on the value property of a formatted text field using the two-argument version of addPropertyChangeListener :

The Property Change Listener API

Registering a PropertyChangeListener

The PropertyChangeListener Interface

Because PropertyChangeListener has only one method, it has no corresponding adapter class.

The PropertyChangeEvent Class

Examples that Use Property Change Listeners

The following table lists the examples that use property-change listeners.

About Oracle | Contact Us | Legal Notices | Terms of Use | Your Privacy Rights

Copyright © 1995, 2022 Oracle and/or its affiliates. All rights reserved.

IMAGES

  1. property.change event

    property change event

  2. java

    property change event

  3. 36 Javascript Property Change Listener

    property change event

  4. Using JoltBeans

    property change event

  5. One Property Can Change Your Life

    property change event

  6. Dropdown selected change event in jQuery Example

    property change event

COMMENTS

  1. Property change events - WPF .NET | Microsoft Learn

    Generally, the property changed event is provided so that you can respond to the value change in other logic areas of your code. Changing the property value again from within the property changed event handler isn't advisable, and can cause unintentional recursion depending on your handler implementation.

  2. PropertyChangeEvent (Java Platform SE 8 ) - Oracle

    A "PropertyChange" event gets delivered whenever a bean changes a "bound" or "constrained" property. A PropertyChangeEvent object is sent as an argument to the PropertyChangeListener and VetoableChangeListener methods. Normally PropertyChangeEvents are accompanied by the name and the old and new value of the changed property.

  3. Raise an event whenever a property's value changed?

    6 Answers. Sorted by: 172. The INotifyPropertyChanged interface is implemented with events. The interface has just one member, PropertyChanged, which is an event that consumers can subscribe to. The version that Richard posted is not safe. Here is how to safely implement this interface: public class MyClass : INotifyPropertyChanged { private ...

  4. Property-Changed Events - Windows Forms .NET Framework

    Property-Changed Events. If you want your control to send notifications when a property named PropertyName changes, define an event named PropertyName Changed and a method named On PropertyName Changed that raises the event. The naming convention in Windows Forms is to append the word Changed to the name of the property.

  5. PropertyChangeEvent (Java SE 17 & JDK 17) - Oracle

    A "PropertyChange" event gets delivered whenever a bean changes a "bound" or "constrained" property. A PropertyChangeEvent object is sent as an argument to the PropertyChangeListener and VetoableChangeListener methods. Normally PropertyChangeEvents are accompanied by the name and the old and new value of the changed property.

  6. How to: Implement Property Change Notification - WPF .NET ...

    To implement INotifyPropertyChanged you need to declare the PropertyChanged event and create the OnPropertyChanged method. Then for each property you want change notifications for, you call OnPropertyChanged whenever the property is updated. To see an example of how the Person class can be used to support TwoWay binding, see Control When the ...

  7. HTMLElement: change event - Web APIs | MDN - MDN Web Docs

    HTMLElement: change event. The change event is fired for <input>, <select>, and <textarea> elements when the user modifies the element's value. Unlike the input event, the change event is not necessarily fired for each alteration to an element's value. Depending on the kind of element being changed and the way the user interacts with the ...

  8. How to Write a Property Change Listener - Oracle

    Property-change events occur whenever the value of a bound property changes for a bean — a component that conforms to the JavaBeans™ specification. You can find out more about beans from the JavaBeans trail of the Java Tutorial. All Swing components are also beans.