WPF TextBox validation 2

Many people asked me how to enable/disable button depending on a few TextBoxes. I would strongly recommend Caliburn but I know not everyone can use it. So I’ve decided to post a very simple solution to that problem.

First of all we need a ViewModel and I will use a very simple class which has IsValid method – checking if data is valid, ICommand property to be bound to a Button and an action to be executed when the button is pressed.

    class PersonViewModel
{
public string Name { get; set; }
public int Age { get; set; }

public bool IsValid()
{
if(string.IsNullOrEmpty(this.Name))
{
return false;
}
if(this.Age < 5 || this.Age > 120)
{
return false;
}
return true;
}

public ICommand OkCommand
{
get { return new DelegatedCommand(this.OkAction, this.IsValid); }
}

private void OkAction()
{
MessageBox.Show("ok!");
}
}

TextBox.Text properties can now be bound to properties of this class and button’s command can be bound to OkCommand. Automatically button will be enable when command can be executed and disabled when command cannot be executed:

<TextBox Text="{Binding Path=Name}"/>
<TextBox Text="{Binding Path=Age}"/>
<Button Command="{Binding Path=OkCommand}" Content="ok"/>

My ICommand implementation in this example is very naive. Maybe a better one in a next post? :-)

Results disabled and enabled:

image image

Code here

Monika

1 Comment

  • Very cool, although I agree that the implementation is naive.

    Also, you'd never ever want to hardcode rules validation like this.
    You should try using one of validation frameworks, like Castle Validator component. (NHibernate Validator could be used as well, I supposed, although I'm nor sure it's suitable for UI validation)

Comments have been disabled for this content.