Search code examples
c#wpfbindingverification

How to check data when using binding in WPF


Maybe this is easy, but I didn't find a solution for my problem yet.

When I use binding and a user changes for example the text in a textbox, how can I perform some backround checks like:

  • Is this name already in my database
  • Does the name fit to my allowed character set

Without binding this is easy i just call the functions that do the trick.

Example:

<TextBox x:Name="textbox_Name" Height="23" Margin="108,37,20,0" TextWrapping="Wrap" Text="{Binding Name,UpdateSourceTrigger=LostFocus}" VerticalAlignment="Top"/>
  • The datacontext is ObjectXYZ.
  • ObjectXYZ has a Name and a Description property.
  • I also have a Database with a ObservableCollection of type "ObjectXYZ" called "list"

Normaly I woud do something like: if(!Database.isExistingObject(textbox_Name.Text) { ObjectXYZ.Name=textbox_Name.Text; }

With binding the name gets directly changed(Two way binding)...how can I check it before its changed?


Solution

  • You can still call your background checks if you call them right after the user has updated the textbox content.

    private string name;
    
    public string Name 
    {
        get
        {
            return name;
        }
    
        set
        {           
            CheckName(value); // Or whatever are you check functions
    
            name = value;
    
            PropertyChanged("Name");
        }
    }
    

    I hope this helps.