简体   繁体   中英

Validation and last value of textbox on MVVM

I have such textbox declaration:

<TextBox x:Name="InputTextBox">
                <Binding Path="Input" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
                    <Binding.ValidationRules>
                        <MyValidationRule
                        ErrorMessage="Invalid" />
                    </Binding.ValidationRules>
                </Binding>
                <TextBox.InputBindings>
                    <KeyBinding Key="Enter" Command="{Binding Path=AddCommand}"/>
                </InputBindings> 
  </TextBox>

Such validationRule hierarchy:

public abstract class AbstractValidationRule : ValidationRule
{
    public string ErrorMessage { get; set; }

    protected abstract bool IsValid(string inputString)

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        string inputString = (value ?? string.Empty).ToString();

        if (!IsValid(inputString)) return new ValidationResult(false, ErrorMessage);
        return new ValidationResult(true, null);
    }
}

class MyValidationRule : AbstractStringValidationRule
{
    protected override bool IsValid(string inputString)
    {
        return !String.IsNotNullOrEmpty(inputString);
    }
}

Add command:

    public ICommand AddCommand
    {
        get
        {
            return m_AddCommand ??
                   (m_AddCommand = new DelegateCommand(Add));
        }
    }

private void Add()
    {
        InternalValue = Input;
        // input = Old invalid value
        OnPropertyChanged("Input")
    }

Input property:

  public string Input
    {
        get { return m_Input; }
        set
        {
            if (m_Input != value)
            {
                m_Input = value;
                OnPropertyChanged("Input");
            }
        }
    }

If I entered "valid" and then "invalid", When command was executed, property Input will be set in "valid" value state. I tried another way with UpdateSourceTrigger="Explicit" and using TextChanged event - was still same result.

Without ValidationRule - all works good.

PS I cannot change class from model layer.

嗨,设置UpdateSourceTrigger =“ PropertyChanged”。希望这会有所帮助。

if you want that your validation/viewmodel and your "ui" are in sync then you should use IDataErrorInfo. your Input property should hold "valid" AND "invalid" values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM