#149 – Use PropertyChanged and Coercion Callbacks to Force Dependencies Between Properties

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:

  • BirthYear
    • In PropertyChangedCallback, force coercion of DeathYear and MarriageYear
  • DeathYear
    • In PropertyChangedCallback, force coercion of MarriageYear
    • In CoerceValueCallback, if value earlier than birth, set to BirthYear
  • MarriageYear
    • In CoerceValueCallback, if marriage earlier than birth, set to birth year; if later than death, set to death year

Here’s an example.

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #149 – Use PropertyChanged and Coercion Callbacks to Force Dependencies Between Properties

  1. Pingback: #150 – An Example of Using PropertyChanged and CoerceValue Callbacks « 2,000 Things You Should Know About WPF

  2. Pingback: #158 – When to Create a Custom Dependency Property « 2,000 Things You Should Know About WPF

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: