I have a ListBox with SelectionMode set to Multiple. I'd like to add special data validation to the control so that if you select all of the items, the ListBox gets the red border and has a "You cannot select all of the items" error message.
I was able to get it to work--but it's a hack. I'm hoping there's a cleaner way to do this. Here's my current solution:
XAML:
<ListBox x:Name="ListBox" SelectionMode="Multiple" Tag="{Binding ErrorTag, Mode=TwoWay, ValidatesOnExceptions=True}" SelectionChanged="ListBox_SelectionChanged" />
ErrorTag Property:
public string ErrorTag
{
get
{
return _ErrorTag;
}
set
{
_ErrorTag = value;
if (_ErrorTag != null)
{
throw new Exception(_ErrorTag);
}
}
}
private string _ErrorTag;
ListBox Selection Changed event:
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ListBox.SelectedItems.Count == ListBox.Items.Count)
{
ListBox.Tag = "You cannot select everything";
}
else
{
ListBox.Tag = null;
}
}
See what I mean? Hack. :-) Any suggestions for a better solution?
Note: This would be easy if I could data bind to the SelectedItems property, but I guess that's just not possible (see http://blog.functionalfun.net/2009/02/how-to-databind-to-selecteditems.html).