December 8, 2010 2 Comments
When implementing dependency properties, you typically use the CoerceValueCallback and PropertyChangedCallbacks to enforce relationships between properties.
For example, assume we have a Person class with BirthYear, DeathYear and MarriageYear properties. We want to ensure that MarriageYear is never earlier than BirthYear or later than DeathYear. We want these checks done any time that we change any of the three properties.
The basic plan is:
- Allow setting BirthYear to anything
- When setting DeathYear, don’t let it be earlier than BirthYear
- When setting MarriageYear, don’t let it be earlier than birth or later than death
When registering the dependency properties, we therefore do the following:
- In PropertyChangedCallback, force coercion of DeathYear and MarriageYear
- In PropertyChangedCallback, force coercion of MarriageYear
- In CoerceValueCallback, if value earlier than birth, set to BirthYear
- In CoerceValueCallback, if marriage earlier than birth, set to birth year; if later than death, set to death year
Here’s an example.