This project is read-only.

TextBox Validation

Jan 13, 2011 at 2:18 PM

hi,

In my app I have a View and a Coresponding ViewModel. My View has a TextBox which has a Binding to property in the ViewModel. In my View I also have a Button which has a Binding to a command in the VM. Now when the command executes I would like to invoke validation so if any the validation error will appear. Any ideas on how to do it?

Jan 13, 2011 at 2:28 PM

Unfortunatly is doesn't :(

I know how to setup validation but it works when a user click inside the textbox and the looses focus. I want it to work specifically when a user click a button. The user may never click inside the textbox so that kind of validation is usesless for me.

Jan 13, 2011 at 2:56 PM

Still can't get it to work :/

Here are some relevant code samples

View:

<TextBox
                    Grid.Column="1"
                    Grid.Row="1"
                    Width="200"
                    Text="{Binding NazwaUzytkownika, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}"/>

<Button
                    Grid.Column="1"
                    Grid.Row="3"
                    HorizontalAlignment="Right"
                    Content="Zaloguj"
                    Command="{Binding Zaloguj}"/> 
ViewModel:
[MapViewModel(typeof(MainPage))]
public class MainPageViewModel: ViewModelBase
{
private string _nazwaUzytkownika = string.Empty;

private ICommand _zaloguj;

public Action UI { get; set; }

[Required(ErrorMessage="Nazwa użytkownika jest wymagana")]
        public string NazwaUzytkownika
        {
            get
            {
                return _nazwaUzytkownika;
            }
            set
            {
                Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "NazwaUzytkownika" }); 
                _nazwaUzytkownika = value;
                NotifyPropertyChanged(() => NazwaUzytkownika);
            }
        }

[ResolveConstructor]
        public MainPageViewModel()
        {
            UI = ((uiAction) => uiAction());
            _zaloguj = new ActionCommand(WykonajZaloguj);         
        }

private void WykonajZaloguj()
        {
            UI(() =>
                {
                    Validator.ValidateProperty(NazwaUzytkownika, new ValidationContext(this, null, null) { MemberName = "NazwaUzytkownika" });
                });
        }
}
And I get some strange NullReferenceException which is not even catched by VS :/