views:

338

answers:

1

I want to use ValidationRules to verify that a few ListBox controls have at least one item selected.

I tried doing it this way:

<ListBox ItemsSource="{Binding Path=AvailableItems}"
         Behaviors:MultiSelectorBehaviours.SynchronizedSelectedItems="{Binding ChosenItems}"
         x:Name="ListBoxItems">  
    <ListBox.Tag>
        <Binding ElementName="ListBoxItems" Path="SelectedItem">
            <Binding.ValidationRules>
                <ValidationRules:NotNullValidationRule />
            </Binding.ValidationRules>
        </Binding>
    </ListBox.Tag>
</ListBox>

But my NotNullValidationRule never gets called. Note that the SynchronizedSelectedItems is a special attached property I use to synchronize the SelectedItems to a custom collection (described here). That's why I do my validation on a 'fake' Binding applied to Tag instead.

Is there a way to validate ListBox.SelectedItems?

+1  A: 

Validation is done only in TwoWay and OneWayToSource mode bindings. If you turn the Binding around, binding SelectedItem to tag in either TwoWay or OneWayToSource mode the validation is triggered.

Validation is there to protect the target property. So when you set Tag, validation makes sure the Tag is valid and SelectedItem can be set with a new value. The following code works (SelectedItem binds TwoWay automatically IIRC.)

<ListBox x:Name="list">
    <ListBox.SelectedItem>
        <Binding ElementName="list" Path="Tag">
            <Binding.ValidationRules>
                <local:SelectedValidationRule />
            </Binding.ValidationRules>
        </Binding>
    </ListBox.SelectedItem> 
</ListBox>
Mikko Rantanen
Thanks! Works just like I want now.
Anthony Brien