Since I’ve started in with WPF (2007) I’ve seen many people creating Validation.ErrorTemplates with the following Binding to display the error message
{Binding ElementName=customAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}
When this binding is used you will see the following errors appear in the Debug Output window:
System.Windows.Data Error: 16 : Cannot get ‘Item[]‘ value (type ‘ValidationError’) from ‘(Validation.Errors)’ (type ‘ReadOnlyObservableCollection`1′). BindingExpression:Path=AdornedElement.(0).[0].ErrorContent; DataItem=’AdornedElementPlaceholder’ (Name=’customAdorner’); target element is ‘TextBlock’ (Name=”); target property is ‘ToolTip’ (type ‘Object’) TargetInvocationException:’System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. —> System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
at System.ThrowHelper.ThrowArgumentOutOfRangeException()
at System.Collections.Generic.List`1.get_Item(Int32 index)
at System.Collections.ObjectModel.Collection`1.get_Item(Int32 index)
at System.Collections.ObjectModel.ReadOnlyCollection`1.get_Item(Int32 index)
— End of inner exception stack trace —
at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at MS.Internal.Data.PropertyPathWorker.GetValue(Object item, Int32 level)
at MS.Internal.Data.PropertyPathWorker.RawValue(Int32 k)’
When you change the Binding from
{Binding ElementName=customAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}
To
{Binding ElementName=customAdorner, Path=AdornedElement.(Validation.Errors)/ErrorContent}
All the exception related to the [0] will be a thing of the past as the / will bind to the current item of the collection and will not cause a any errors if there is no current item.
This could also be used when you have a collection of items and want to display the current item’s properties on a UI (View).
Hope this post can help other people.
Kind regards,
Johan J v Rensburg
Example Source Code: DataBinding CurrentItem.rename_to_zip