L’attributo AmbientValue

Shawn Burke in un thread su .NET 247 chiarisce l’utilizzo dell’attributo AmbientValue:

Shawn Burke [MSFT]
AmbientValueAttribute is for properties that inherit settings from other places. For example the Font or Cursor properties on Control will report their Parent’s value if they aren’t set. But the code generation engine doesn’t know this. The most common place that we use this is undo/redo.

Say you add a Button to a Form. The Button will get the same Font as the form has — it inherits that value. But since no value has actually been set, the codegen engine still doesn’t want to generate code for the Font property (since doing so would break the ambient property inheritance). For the case of the Font property, setting the value “null” into the property will put it back into the inheriting state. We added this because the AmbientValue is just a little different from the DefaultValue since setting the DefaultValue will “reset” a property to an intial state but will stop value inheritance from working.

Now think about the undo/redo case:

1) Button is placed on Form, Font=”Ms Sans Serif”
2) User changes Button Font=”Arial”
3) Undo engine sees this change, but sees that the Button.Font property is in a “default” state
4) There is no DefaultValueAttribute on Button.Font because we’re in a state where the “default” value is different from the internal value (inherited versus null), so the undo engine can handle this by looking for the AmbientValueAttribute, which has “null” in it.
5) Undo engine finds the AmbientValueAttribute, and saves “null” as the way to put the Button.Font property back in the state of (1) above.

This posting is provided “AS IS” with no warranties, and confers no rights. You assume all risk for your use. © 2001 Microsoft Corporation. All rights reserved.

Sempre dello stesso autore questo interessante articolo (anche se un po’ datato):

Customizing Code Generation in the .NET Framework Visual Designers