Sunday, May 15, 2011

Validation In Silverlight 4


The new Validation states for controls in Silverlight 4 sure look nice but there are a number of limitations. For starters, you can only invoke them through:
  • An exception thrown by a bound property setter
  • An exception thrown by a ValueConverter
The latter feels particularly unsavoury as you'll need to reuse the same converter wherever you want to bind to that property - a big violation of the DRY principle.
You can't even use the new ValidationAttributes from System.ComponentModel.DataAnnotations. Well, actually you can but you'd have to this inside the setter:


 private string _ArtCategory;


        public string ArtCategory
        {
            get { return _ArtCategory; }
            set 
            {
                   if(value=="")
                       {
                           throw new Exception("Invalid Category!!");
                       }
                    else
                   _ArtCategory = value;
            }
        }


And This is bound to a TextBox: 




<TextBox Height="23" Text="{Binding Path=ArtCategory,Mode=TwoWay,ValidatesOnExceptions=True,NotifyOnValidationError=True}" HorizontalAlignment="Left" Margin="119,3,0,0" Name="txtCategory" VerticalAlignment="Top" Width="231" />




Now, to get this working on any scale is going to require code-behind. Lots of code-behind. And everybody knows I hate this. The whole validation story at the moment isn't going to play at all well with Model-View-ViewModel (MVVM).