Search code examples
c#wpfvalidationxamldata-binding

WPF Binding in TextBlock.Text to Validation.Errors not working


I have an ItemsControl which is validated by an object on the DataContext that implements INotifyDataErrorInfo. The intended effect is for the validation error to show below the control in a TextBlock, rather than the conventional red border and tooltip style.

Upon validation, my TextBlock appears, but it's Text is empty - there's something wrong with my binding to the validation error, but I can't figure out what.

Also, the TextBlock overlaps the control below the ItemsControl it rather than making extra space for itself. How can I solve these issues?

<ItemsControl ...>
    <Validation.ErrorTemplate>
        <ControlTemplate>
            <StackPanel>
                <AdornedElementPlaceholder />
                <TextBlock Text="{Binding RelativeSource={RelativeSource Self},
                    Path=(Validation.Errors).CurrentItem.ErrorContent}" />
            </StackPanel>
        </ControlTemplate>
    </Validation.ErrorTemplate>
</ItemsControl>

Solution

  • I got the same problem as your first issue a few days ago. When I examine the control inside the ErrorTemplate by using Snoop, I found out that the DataContext inside the ErrorTemplate is already of type ReadOnlyObservableCollection<ValidationError>. So you can just use <TextBlock Text="{Binding CurrentItem.ErrorContent}" />, no need for casting and setting the RelativeResource.