When you’re working with WCF RIA Services, there are various ways to handle your validation: you can use the built-in data annotations, you can write custom validators on property level, on entity level, you can do cross-field validation, … and sometimes, you’ll need information in your validators that isn’t related to your Entity. For example: your validation rule could be different depending on the role of the logged in user, depending on the location he’s at, …
For scenarios like this, you can use the ValidationContext: you can pass in a Dictionary<object, object> containing any state information you might need to ensure your validation rule works as expected. For more information on this, you can find a great explanation at Jeff Handley’s blog.
That said, when you’re working with this, you might notice something strange when you put breakpoints in your validator: even though you’re passing in the correct state information through the ValidationContext, sometimes the Items collection might seem empty (just have a look around the internet, and you’ll notice quite a few people ran into this problem). When someone mentions this problem, they’re typically using controls like a DataForm or DataGrid. So, why is this?
Well: validation can be triggered at different moments, and by different controls. Take a DataGrid for example: it triggers its own validation (for example: when you start editing a property). But the DataGrid control doesn’t have any knowledge of WCF RIA Services (Jeff also mentions this in his posts: you can never assume your validator will have access to the Items collection!). So: when validation is triggered by the DataGrid, it will execute the validators without the custom ValidationContext – therefore, the Items collection is empty (the same applies to services you provide) in those cases.
Luckily, validation is also triggered in the property setters (amongst other places), which does provide the correct ValidationContext, ensuring our validator works as expected.