Wpf prism Notify property changed with validation not set

Viewed 428

I just started using a prism with wpf and don’t understand why my property is not being updated. I have a binding to a text block with validation and it works until I delete the last character. I looked through the debugger, and the set property is not called, but the validation method is called. Also, I don’t understand how updating the can executing method works. It fires returns true when I enter a character in a textbox, but after deletion it does not update. I will be grateful for the answer, here is my code.

My viewmodel (this command in constructor)

SaveCommand = new DelegateCommand(ExecuteSaveCommand, CanExecuteSaveCommand);

 public string ImageTitle
 {
      get => _userImageModel.Title;
      set
      {
          _userImageModel.Title = value;
          RaisePropertyChanged(); 
          SaveCommand.CanExecute();
      }
 }

private bool CanExecuteSaveCommand()
{
        var x = string.IsNullOrWhiteSpace(_userImageModel.Title) == false || 
                                              _userImageModel.Title!=null;
        return x;
}

My validation rule

public class UserImageValidator : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        if (value == null)
            return new ValidationResult(false,"value cannot be empty");

        if(!(value is string propertyValue))
            return new ValidationResult(false,"exception");

        if(string.IsNullOrWhiteSpace(propertyValue))
            return new ValidationResult(false,"Required");

        return ValidationResult.ValidResult;
    }
}

My view

 <TextBox
        Grid.Row="0"
        Grid.Column="1"
        MinWidth="200"
        Margin="5"
        VerticalAlignment="Center"
        MinLines="4"
        Validation.ErrorTemplate="{StaticResource ErrorTemplate}">
        <TextBox.Text>
          <Binding Path="ImageTitle" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
              <validateRule:UserImageValidator />
            </Binding.ValidationRules>
          </Binding>
        </TextBox.Text>
      </TextBox>
3 Answers

I don’t understand how updating the can executing method works.

You call RaiseCanExecuteChanged on the command instead. The framework calls CanExecute to determine whether a button is enabled or not, for example.

Also, string.IsNullOrWhiteSpace(_userImageModel.Title) == false || _userImageModel.Title!=null doesn't make a lot of sense (!= null is true for a white space string), do you mean !string.IsNullOrWhiteSpace( _userImageModel.Title )?

check this property, _userImageModel.Title, it sets the property there. Also SaveCommand is not hooked to the textbox.

Related