Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 66 additions & 7 deletions src/Controls/src/SourceGen/KnownMarkups.cs
Original file line number Diff line number Diff line change
Expand Up @@ -341,16 +341,31 @@ private static bool ProvideValueForBindingExtension(ElementNode markupNode, Inde
returnType = context.Compilation.GetTypeByMetadataName("Microsoft.Maui.Controls.BindingBase")!;
ITypeSymbol? dataTypeSymbol = null;

// When Source is explicitly set (RelativeSource or x:Reference), x:DataType does not describe
// the actual source — skip compilation and fall back to runtime binding.
bool hasExplicitSource = HasExplicitBindingSource(markupNode);

context.Variables.TryGetValue(markupNode, out ILocalValue? extVariable);

if ( !hasExplicitSource
&& extVariable is not null)
if (extVariable is not null)
{
TryGetXDataType(markupNode, context, out dataTypeSymbol);
// Determine the source type for compiled binding based on the binding's Source configuration:
//
// 1. RelativeSource with a resolvable AncestorType: use the AncestorType as the source
// type. The symbol is already registered in context.Types by
// ProvideValueForRelativeSourceExtension, enabling trim-safe TypedBinding generation.
//
// 2. RelativeSource without AncestorType (Self, TemplatedParent, or FindAncestor without
// a type): the binding source is resolved at runtime. Using x:DataType as the source
// type here would produce a compiled binding with an incorrect source type, leading to
// runtime failures. Fall through to the string-based Binding path instead.
//
// 3. No RelativeSource: use x:DataType if available to produce a compiled TypedBinding.
if (TryGetRelativeSourceAncestorType(markupNode, context, out var ancestorTypeSymbol)
&& ancestorTypeSymbol is not null)
{
dataTypeSymbol = ancestorTypeSymbol;
}
else if (!HasExplicitBindingSource(markupNode))
{
TryGetXDataType(markupNode, context, out dataTypeSymbol);
}

if (dataTypeSymbol is not null)
{
Expand Down Expand Up @@ -653,6 +668,50 @@ static bool HasExplicitBindingSource(ElementNode bindingNode)

return false;
}

// Checks if the binding has a Source property that is a RelativeSource extension
// with a resolvable AncestorType. If so, returns the already-resolved AncestorType
// symbol from context.Types (populated earlier by ProvideValueForRelativeSourceExtension).
// This allows AncestorType bindings to use the compiled (trim-safe) TypedBinding path.
static bool TryGetRelativeSourceAncestorType(ElementNode bindingNode, SourceGenContext context, out ITypeSymbol? ancestorType)
{
ancestorType = null;

// Check if Source property exists
if (!bindingNode.Properties.TryGetValue(new XmlName("", "Source"), out INode? sourceNode)
&& !bindingNode.Properties.TryGetValue(new XmlName(null, "Source"), out sourceNode))
{
return false;
}

// Check if the Source is a RelativeSourceExtension
if (sourceNode is not ElementNode relativeSourceNode
|| (relativeSourceNode.XmlType.Name != "RelativeSourceExtension"
&& relativeSourceNode.XmlType.Name != "RelativeSource"))
{
return false;
}

// Find the AncestorType property on the RelativeSource node
if (!relativeSourceNode.Properties.TryGetValue(new XmlName("", "AncestorType"), out INode? ancestorTypeNode)
&& !relativeSourceNode.Properties.TryGetValue(new XmlName(null, "AncestorType"), out ancestorTypeNode))
relativeSourceNode.Properties.TryGetValue(new XmlName(XamlParser.MauiUri, "AncestorType"), out ancestorTypeNode);

if (ancestorTypeNode is null)
{
return false;
}

// The AncestorType is typically an x:Type extension (ElementNode).
// ProvideValueForRelativeSourceExtension already resolved this type
// and registered it in context.Types — just look it up.
if (ancestorTypeNode is ElementNode typeExtNode)
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Source={RelativeSource AncestorType={local:Maui34056PageViewModel}} is also valid syntax and in that case I believe ancestorTypeNode would be a ValueNode with a string value, although I might be wrong. We should have a test case for this scenario too and make sure it works too.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@simonrozsival, I investigated the syntax {local:Maui34056PageViewModel} and confirmed that it is not valid XAML.

The XAML compiler throws MAUIG1001: "Invalid RelativeSource Mode '(none)'" at build time because {local:...} is not a markup extension and cannot return a System.Type.

Based on official documentation, the AncestorType property must always receive a valid Type. As documented:
“The AncestorType property must be set to a Type… otherwise a XamlParseException is thrown.”
Therefore, the only valid syntax is:

{x:Type local:Maui34056PageViewModel}

This valid form is already handled by the current fix, so no additional code change or test is required for this scenario.

Documentation: https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/data-binding/relative-bindings?view=net-maui-10.0#bind-to-an-ancestor

{
return context.Types.TryGetValue(typeExtNode, out ancestorType) && ancestorType is not null;
}

return false;
}
}

internal static bool ProvideValueForDataTemplateExtension(ElementNode markupNode, IndentedTextWriter writer, SourceGenContext context, NodeSGExtensions.GetNodeValueDelegate? getNodeValue, out ITypeSymbol? returnType, out string value)
Expand Down
33 changes: 33 additions & 0 deletions src/Controls/tests/Xaml.UnitTests/Issues/Maui34056.xaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:Microsoft.Maui.Controls.Xaml.UnitTests"
x:Class="Microsoft.Maui.Controls.Xaml.UnitTests.Maui34056"
x:DataType="local:Maui34056PageViewModel">
<VerticalStackLayout>
<!-- Scenario 1: RelativeSource AncestorType inside DataTemplate with x:DataType (issue fix) -->
<CollectionView x:Name="TestCollectionView"
ItemsSource="{Binding Items}">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="local:Maui34056ItemViewModel">
<Button x:Name="TestButton"
Text="{Binding ItemName}"
Command="{Binding x:DataType='local:Maui34056PageViewModel', Source={RelativeSource AncestorType={x:Type local:Maui34056PageViewModel}}, Path=TestCommand}" />
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>

<!-- Scenario 2: {RelativeSource Self} inside DataTemplate with x:DataType.
SourceGen must not use x:DataType as the source type; the source is the element itself.
Path=ItemName exists on Maui34056ItemViewModel to ensure the guard, not a failed lookup, prevents compiled binding. -->
<CollectionView x:Name="SelfBindingCollectionView"
ItemsSource="{Binding Items}">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="local:Maui34056ItemViewModel">
<Label x:Name="SelfBindingLabel"
Text="{Binding Path=ItemName, Source={RelativeSource Self}}" />
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</VerticalStackLayout>
</ContentPage>
93 changes: 93 additions & 0 deletions src/Controls/tests/Xaml.UnitTests/Issues/Maui34056.xaml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
using System.Collections.ObjectModel;
using System.Windows.Input;
using Microsoft.Maui.Controls.Internals;
using Xunit;

namespace Microsoft.Maui.Controls.Xaml.UnitTests;

// Page-level ViewModel — this is what the RelativeSource AncestorType points to
public class Maui34056PageViewModel
{
public ObservableCollection<Maui34056ItemViewModel> Items { get; } =
[new Maui34056ItemViewModel { ItemName = "Item 1" }];

public ICommand TestCommand { get; } = new Command(() => { });
}

// Item ViewModel — this is what the DataTemplate's x:DataType is set to
public class Maui34056ItemViewModel
{
public string ItemName { get; set; } = "";
}

public partial class Maui34056 : ContentPage
{
public Maui34056()
{
InitializeComponent();
BindingContext = new Maui34056PageViewModel();
}

[Collection("Issue")]
public class Maui34056Tests
{
[Theory]
[XamlInflatorData]
internal void RelativeSourceAncestorTypeInDataTemplateGeneratesCompiledBinding(XamlInflator inflator)
{
var page = new Maui34056(inflator);

var template = ((CollectionView)page.TestCollectionView).ItemTemplate;
var content = template.CreateContent() as Button;
Assert.NotNull(content);

var bindingContext = content.GetContext(Button.CommandProperty);
Assert.NotNull(bindingContext);
var binding = bindingContext.Bindings.GetValue();

if (inflator is XamlInflator.Runtime)
{
// Runtime inflator uses the string-based Binding — no compile-time type info available.
Assert.IsType<Binding>(binding);
}
else
{
// Both XamlC and SourceGen produce a trim-safe TypedBinding when x:DataType is present
// on the binding node alongside RelativeSource AncestorType.
Assert.IsType<TypedBinding<Maui34056PageViewModel, ICommand>>(binding);
}
}

[Theory]
[XamlInflatorData]
internal void RelativeSourceSelfInDataTemplateWithXDataTypeUsesStringBinding(XamlInflator inflator)
{
// Verifies SourceGen does not use the DataTemplate's x:DataType as the source type for
// {RelativeSource Self} bindings. The source is the element itself, resolved at runtime.
// Path=ItemName exists on Maui34056ItemViewModel to ensure the guard is what prevents
// compiled binding, not a failed type lookup. XamlC behavior is pre-existing and separate.
var page = new Maui34056(inflator);

var template = ((CollectionView)page.SelfBindingCollectionView).ItemTemplate;
var content = template.CreateContent() as Label;
Assert.NotNull(content);

var bindingContext = content.GetContext(Label.TextProperty);
Assert.NotNull(bindingContext);
var binding = bindingContext.Bindings.GetValue();

if (inflator is XamlInflator.XamlC)
{
// XamlC pre-existing behavior: compiles RelativeSource Self using DataTemplate x:DataType.
// This is a separate issue, not addressed by this fix.
Assert.IsType<TypedBinding<Maui34056ItemViewModel, string>>(binding);
}
else
{
// Runtime: no compile-time type info, always string-based Binding.
// SourceGen (the fix): HasRelativeSourceBinding blocks x:DataType path for Self bindings.
Assert.IsType<Binding>(binding);
}
}
}
}
Loading