views:

328

answers:

1

I'm trying to write a custom WPF ValidationRule to enforce that a certain property is unique within the context of a given collection. For example: I am editing a collection of custom objects bound to a ListView and I need to ensure that the Name property of each object in the collection is unique. Does anyone know how to do this?

+2  A: 

First, I'd create a simple DependencyObject class to hold your collection:

class YourCollectionType : DependencyObject {

    [PROPERTY DEPENDENCY OF ObservableCollection<YourType> NAMED: BoundList]

}

Then, on your ValidationRule-derived class, create a property:

YourCollectionType ListToCheck { get; set; }

Then, in the XAML, do this:

<Binding.ValidationRules>
    <YourValidationRule>
       <YourValidationRule.ListToCheck>     
          <YourCollectionType BoundList="{Binding Path=TheCollectionYouWantToCheck}" />
       </YourValidationRule.ListToCheck>
    </YourValidationRule>
</Binding.ValidationRules>

Then in your validation, look at ListToCheck's BoundList property's collection for the item that you're validating against. If it's in there, obviously return a false validation result. If it's not, return true.

Daniel Jennings
This doesn't seem to work, the binding result is always null (doesn't seem to inherit the DataContext)
Flatliner DOA