Validation when adding a new item and no target to source binding has yet taken place RRS feed

  • Question

  • Using: WPF (.NET 4) with Entity Framework on a SQLCE database.

    In my app, the user can edit existing employees and create new employees. The same UI control is used to add and edit. In the case of editing an Employee, the DataContext for the control is the Employee object of my Entity Framework context. It is updated through binding, and the SaveChanges method is called on my EF to update the database. In the case of adding and Employee, the DataContext is a new Employee object, which will gets added to the EF and then saved. Simple.

    I've been trying to hook-up validation to the control. I'm using WPF's ValidationRule objects for each field binding as required. When the field loses focus (as is the default action for a target to source binding), the validation rules are checked, which can incur an error. I can then check for the presence of these errors before allowing the employee to be saved.

    But when adding a new Employee, if I go ahead and push the Save button without doing anything else, no validation takes place, becasue the bindings have never attempted to update the source! It just throws an exception as expected.

    What can I do? I have ideas which would probably work, but I thought I should post here first in case I am missing something obvious! Is there a standard way to deal with this situation? Do I have to manually update each binding myself when adding? Write extra validation code?


    Monday, November 29, 2010 12:24 PM


All replies

  • I have it working by manually looping through each TextBox in my control, testing to see if it has a BindingExpression on the TextProperty, and if so, calling it's UpdateSource() method. I am not yet checking radiobuttons / comboxes, but I'm sure I could do so in a similair way. I only do this when adding an employee, not when editing obviously.

    But I still wonder whther there is a more elegant way that doesn't require a lot of extra code!

    Monday, November 29, 2010 1:11 PM
  • Hi Rizzlwizzl,


    Thanks for your post.

    As far as I know, your method should work and it is a smart solution.

    --> But I still wonder whether there is a more elegant way that doesn't require a lot of extra code!

    I'm not sure which way is more typical but I've uploaded a sample of validation helper,

    I think you can reuse something efficiency from that.


    Hope this can help.


    Best Regards,

    Ziwei Chen




    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    • Marked as answer by Yves.Z Tuesday, December 7, 2010 3:34 AM
    Wednesday, December 1, 2010 6:28 AM