Silverlight 3 Quick Tip #9: DataBinding with Validation - DevCorner

Silverlight 3 Quick Tip #9: DataBinding with Validation

Silverlight 3 provides validation mechanism while using Two-Way data binding.

Silverlight 3 also provides default a Validation Exception UI – callout with exception details, which could be customized.

Many input-related controls such as TextBox, CheckBox, etc. have built-in support for validation.

How to use? Simple, like everything with Silverlight: To enable validation, use the ValidatesOnExceptions property.

<TextBox Text="{Binding ID, Mode=TwoWay, ValidatesOnExceptions=True}" />

//Code behind – property definition
public string ID { get { return id; } set { if (string.IsNullOrEmpty(value)) throw new Exception("This field can't be empty!"); id = value; } }
image 

Example on ListBox:

<ListBox SelectedItem="{Binding Score,Mode=TwoWay,ValidatesOnExceptions=True}">
                    <
sys:String>Best</sys:String>
                    <
sys:String>Good</sys:String>
                    <
sys:String>Ok</sys:String>
                    <
sys:String>Acceptable</sys:String>
                    <
sys:String>Bad</sys:String>
</
ListBox>

//Code behind  property definition

public string Score
        {
            get { return score; }
            set
            {
                string[] acceptable = new string[] { "Ok", "Best", "Good" };

                if (!acceptable.Contains(value))
                    throw new Exception("The '" + value + "' is unacceptable");
                else if (value == "Ok")
                    throw new Exception("Ok is not the expected answer");

                score = value;
            }
        }

Sample UI:

image

Enjoy,

Alex

Published Sunday, June 21, 2009 9:07 AM by Alex Golesh

Comments

# re: Silverlight 3 Quick Tip #9: DataBinding with Validation

In my project i'm  typed like you but it NOT Validation .Help me PLZ!!!!!!!!!!!!!!!!!

Sunday, July 05, 2009 7:29 AM by Name

# re: Silverlight 3 Quick Tip #9: DataBinding with Validation

Could you post/send some repro?

Regards,

Alex

Sunday, July 05, 2009 8:34 AM by Alex Golesh

# re: Silverlight 3 Quick Tip #9: DataBinding with Validation

what can i do if i have ado net and want to save validated data to sql.

but the problem is that i cant modify setters in auto generated class

Tuesday, July 14, 2009 2:17 PM by jt

# re: Silverlight 3 Quick Tip #9: DataBinding with Validation

jt: why you need to modify auto generated class? How ADO.NET stops you to serve as RIA services source, and why you couldn't create full CRUD methods with it?

Alex

Tuesday, July 14, 2009 6:28 PM by Alex Golesh

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: