IDataErrorInfo - not seeing any error message even

2019-05-27 17:33发布

问题:

I have ItemType that implements everything one would need for Validation with the help of IDataErrorInfo interface:

#region IDataErrorInfo implementation
        //WPF doesn't need this one
        public string Error
        { get { return null; } }

        public string this[string propertyName]
        {
            get { return GetValidationError(propertyName); }
        }
        #endregion

        #region Validation
        public bool IsValid
        {
            get
            {
                foreach (string property in ValidatedProperties)
                {
                    if (GetValidationError(property) != null)
                    {
                        return false;
                    }
                }

                return true;
            }
        }

        static readonly string[] ValidatedProperties =
        {
            "Name"
        };

        private string GetValidationError(string propertyName)
        {
            if (Array.IndexOf(ValidatedProperties, propertyName) < 0)
                return null;

            string error = null;

            switch (propertyName)
            {
                case "Name":
                    error = ValidateName();
                    break;
                default:
                    Debug.Fail("Unexpected property being validated on Customer: " + propertyName);
                    break;
            }

            return error;
        }

        string ValidateName()
        {
            if (!IsStringMissing(Name))
            {
                return "Name can not be empty!";
            }

            return null;
        }

        static bool IsStringMissing(string value)
        {
            return string.IsNullOrEmpty(value) ||
                   value.Trim() == String.Empty;
        }
        #endregion

ItemType is wrapped with ItemViewModel. On the ItemViewModel I have a command for when a user clicks the Save Button:

public ICommand SaveItemType
        {
            get
            {
                if (saveItemType == null)
                {
                    saveItemType = new RelayCommand(() => Save());
                }

                return saveItemType;
            }
        }

Then, in the DetailsView, I have the following xaml code:

<TextBlock Text="Name:" />
<TextBox Grid.Column="1" Name="NameTextBox" Text="{Binding Name, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"
                         Validation.ErrorTemplate="{x:Null}" />

<ContentPresenter Grid.Row="13" Grid.Column="2"
                  Content="{Binding ElementName=NameTextBox, Path=(Validation.Errors).CurrentItem}" />

the following architecture going on (it is not clear, but the form is actually an independent xaml file (User Control), where the datacontext of the grid in the form is set to the ObservableCollection):

<Grid DataContext="{Binding Items}">
            <Grid.ColumnDefinitions>
                <ColumnDefinition />
                <ColumnDefinition />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>

The problem that I am having is that error messages are not showing up. When I breakpoint and check if it validates correctly and if I have any error messages, then I do have them. But somehow the error message does not arrive in the xaml.

What is the missing piece of the puzzle?

EDIT - THE MISSING PIECE

Right, so, what it was was the following:

I implemented IDataErrorInfo on my model, but not on the ViewModel that wraps the model. What I had to do was as well was implement the IDataErrorInfo interface on the ViewModel, and get it from the model.

ViewModel Implementation of IDataErrorInfo:

{ get { return (ItemType as IDataErrorInfo).Error; } }

public string this[string propertyName]
{
  get
  {
    return (ItemType as IDataErrorInfo)[propertyName];
  }
}

回答1:

i use the follwoing style to see wether my validation occurs or not.

<Style x:Key="{x:Type TextBox}" TargetType="{x:Type TextBox}">
    <Style.Triggers>>
        <Trigger Property="Validation.HasError" Value="true">
            <Setter Property="ToolTip" Value="{Binding Path=(Validation.Errors).CurrentItem.ErrorContent, RelativeSource={x:Static RelativeSource.Self}}"/>
            <Setter Property="Background" Value="{StaticResource BrushErrorLight}" />
        </Trigger>
    </Style.Triggers>
</Style>

you should see the validationmessage in your tooltip

EDIT:

try to add NotifyOnValidationError=true to your binding

<TextBox Grid.Column="1" Name="NameTextBox" 
         Text="{Binding Name, ValidatesOnDataErrors=True, NotifyOnValidationError=true, UpdateSourceTrigger=PropertyChanged}" />


回答2:

I had a similar problem, and fixed it by putting the validated element inside an AdornerDecorator. Might be worth trying.



标签: wpf mvvm binding