@@ -382,14 +382,26 @@ static IEnumerable<Instruction> CompileBindingPath(ElementNode node, ILContext c
382382
383383 INode dataTypeNode = null ;
384384 IElementNode n = node ;
385+
386+ // Special handling for BindingContext={Binding ...}
387+ // The order of checks is:
388+ // - x:DataType on the binding itself
389+ // - SKIP looking for x:DataType on the parent
390+ // - continue looking for x:DataType on the parent's parent...
391+ IElementNode skipNode = null ;
392+ if ( IsBindingContextBinding ( node ) )
393+ {
394+ skipNode = GetParent ( node ) ;
395+ }
396+
385397 while ( n != null )
386398 {
387- if ( n . Properties . TryGetValue ( XmlName . xDataType , out dataTypeNode ) )
399+ if ( n != skipNode && n . Properties . TryGetValue ( XmlName . xDataType , out dataTypeNode ) )
400+ {
388401 break ;
389- if ( n . Parent is ListNode listNode )
390- n = listNode . Parent as IElementNode ;
391- else
392- n = n . Parent as IElementNode ;
402+ }
403+
404+ n = GetParent ( n ) ;
393405 }
394406
395407 if ( dataTypeNode is null )
@@ -475,6 +487,25 @@ static IEnumerable<Instruction> CompileBindingPath(ElementNode node, ILContext c
475487 yield return Create ( Ldnull ) ;
476488 yield return Create ( Newobj , module . ImportReference ( ctorinforef ) ) ;
477489 yield return Create ( Callvirt , module . ImportPropertySetterReference ( context . Cache , bindingExtensionType , propertyName : "TypedBinding" ) ) ;
490+
491+ static IElementNode GetParent ( IElementNode node )
492+ {
493+ return node switch
494+ {
495+ { Parent : ListNode { Parent : IElementNode parentNode } } => parentNode ,
496+ { Parent : IElementNode parentNode } => parentNode ,
497+ _ => null ,
498+ } ;
499+ }
500+
501+ static bool IsBindingContextBinding ( ElementNode node )
502+ {
503+ // looking for BindingContext="{Binding ...}"
504+ return GetParent ( node ) is IElementNode parentNode
505+ && ApplyPropertiesVisitor . TryGetPropertyName ( node , parentNode , out var propertyName )
506+ && propertyName . NamespaceURI == ""
507+ && propertyName . LocalName == nameof ( BindableObject . BindingContext ) ;
508+ }
478509 }
479510
480511 static IList < ( PropertyDefinition property , TypeReference propDeclTypeRef , string indexArg ) > ParsePath ( ILContext context , string path , TypeReference tSourceRef , IXmlLineInfo lineInfo , ModuleDefinition module )
0 commit comments