1. Value. and 2. HasVa..." /> 1. Value. and 2. HasVa..." /> 1. Value. and 2. HasVa..."/>

Can we set property of source object, on validation?

246 views Asked by At

I have a wpf-mvvm application.

In the below code, "PartBPremiumBuydown" is an instance of a class. which has two properties => 1. Value. and 2. HasValidationError.

Property "Value" is used for binding to textbox. If there is any validation error...Can I set HasValidationError=true ?

  <TextBox  ToolTip="{Binding RelativeSource={RelativeSource Self}, 
                      Path=(Validation.Errors).CurrentItem.ErrorContent}">
                        <TextBox.Text>
                            <Binding Path="PartBPremiumBuydown.Value" 
                                      ValidatesOnDataErrors="True"
                                      UpdateSourceTrigger="PropertyChanged"
                             Converter="{x:Static localns:Converters.DecimalToCurrency}">
                                <Binding.ValidationRules>
                                    <localns:CurrencyRule />
                                </Binding.ValidationRules>
                            </Binding>
                        </TextBox.Text>
                    </TextBox>
1

There are 1 answers

1
Jake Berger On BEST ANSWER

You should have PartBPremiumBuydown implement the IDataErrorInfo interface, similar to the below code:

public string Error { get; private set; }
public string this[string propertyName]
{
    get
    {
        string mError = string.Empty;
        if (propertyName == "Value" 
            && !<insert your rule>)
        {
            mError = "Validation error text."
        }
        Error = mError;
        return (string.IsNullOrWhiteSpace(mError))// if   NOTHING 
            ? null                                // then return null
            : mError;                             // else return error
    }
}

Now, when you bind your TextBox to Value, if the user enters in text which breaks your rule, the validation error will show on the TextBox.