Invalid save control

I have a WPF form with some controls. One control is a text field that indicates a property of the string.enter image description here

defined as follows:

        <TextBox>
            <TextBox.Text>
                <Binding Path="ExtractName" UpdateSourceTrigger="LostFocus">
                    <Binding.ValidationRules>
                        <ExceptionValidationRule />
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>

The binded property is defined as:

    private string _extractName;
    public string ExtractName
    {
        get { return _extractName; }
        set
        {
            var extract_id = (int?) null;
            if(SelectedExtract != null)
            {
                extract_id = SelectedExtract.ExtractId;
            }

            if(SelectedExtract == null)
            if (WebServiceCall.ExtractNameExists(extract_id, value))
            {
                _isExtractNameValid = false;
                throw new ApplicationException("Extract Name already exists");
            }

            if (value == "")
            {
                _isExtractNameValid = false;
                throw new ApplicationException("Extract Name cannot be empty");
            }

            _extractName = value;
            _isExtractNameValid = true;
            RaisePropertyChanged("ExtractName");
        }
    }

This works fine if the user enters a control and writes something in it.

enter image description here

But when the save method is called, I want the control to check all the checks, and if something is wrong, the text box should be painted red.

How to do this from a view model?

+4
source share
2 answers

You can implement IDataErrorInfoby providing a collection of validation results. This would be easier to check before / during the save.

: , . ( , )

:

this.GetType().GetProperties().ToList()
    .ForEach(prop => prop.SetValue(this, prop.GetValue(this, null), null));

IDataErrorInfo

+4

IDataErrorInfo .

 foreach (var item in DataContext.GetChangeSet().Inserts)
 {
    IDataErrorInfo errofInfo = item as IDataErrorInfo;
     if(errofInfo != null && !string.IsNullOrEmpty(errofInfo.Error))
     {
         //// Error Exist;
     }
 }

 foreach (var item in DataContext.GetChangeSet().Updates)
 {
    IDataErrorInfo errofInfo = item as IDataErrorInfo;
     if(errofInfo != null && !string.IsNullOrEmpty(errofInfo.Error))
     {
         //// Error Exist;
     }
 }

.

0

All Articles