Repository navigation
Support xmlns prefixes and attached bindable properties in C# expressions - #35007
Conversation
…ions
- Fix StartsWithMarkupExtension to allow prefix:Type. as type reference
- Add ResolveXmlnsPrefixes: expands xmlns prefixes to fully qualified CLR types
- Add TransformAttachedProperties: rewrites (Type.Prop) to Type.GetProp(target)
- Update spec with ABP section and Type References section
- Add tests for {local:ExprHelper.GetStaticValue()} and {gridChild.(Grid.Row)}
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 35007Or
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 35007" |
There was a problem hiding this comment.
Pull request overview
This PR extends the Controls XAML C# expression source generator to (1) allow referencing types via XAML xmlns prefixes inside expressions and (2) introduce attached bindable property access via (Type.Property) syntax, with accompanying documentation and unit tests.
Changes:
- Add preprocessing to expand
prefix:Typeto fully-qualified CLR type names before compiling expressions. - Add preprocessing to transform
target.(Type.Property)intoType.GetProperty(target)calls. - Update the expressions spec and add SourceGen-focused unit tests covering the new syntax.
Reviewed changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated 6 comments.
Show a summary per file
| File | Description |
|---|---|
| src/Controls/src/SourceGen/CSharpExpressionHelpers.cs | Adds regex-based transforms for xmlns-prefix type expansion and attached property rewrites; adjusts markup-extension disambiguation. |
| src/Controls/src/SourceGen/Visitors/ExpandMarkupsVisitor.cs | Wires the new preprocessing into both ValueNode and MarkupNode expression flows. |
| src/Controls/tests/Xaml.UnitTests/CSharpExpressions.sgen.xaml | Adds XAML cases exercising xmlns-prefix type usage and ABP read from a named element. |
| src/Controls/tests/Xaml.UnitTests/CSharpExpressions.sgen.xaml.cs | Adds helper type and new unit tests asserting the new expression behaviors. |
| docs/specs/XamlCSharpExpressions.md | Documents the new Type References and Attached Bindable Properties features and their intended rules/diagnostics. |
| // Resolve xmlns prefixes (e.g., local:Helper → fully qualified) and ABP syntax (e.g., target.(Grid.Row) → Grid.GetRow(target)) | ||
| expressionCode = CSharpExpressionHelpers.TransformAttachedProperties(expressionCode); | ||
| expressionCode = CSharpExpressionHelpers.ResolveXmlnsPrefixes(expressionCode, node.NamespaceResolver, Context); |
There was a problem hiding this comment.
TransformAttachedProperties() runs before ResolveXmlnsPrefixes(). This prevents attached-property syntax from working when the ABP type uses an xmlns prefix (e.g. this.(ios:Page.Prop)), because the ABP regex won’t match until the prefix is expanded. Consider resolving xmlns prefixes first (or updating the ABP transform to understand prefixed/fully-qualified type names) so the two features compose as documented.
| // Resolve xmlns prefixes (e.g., local:Helper → fully qualified) and ABP syntax (e.g., target.(Grid.Row) → Grid.GetRow(target)) | |
| expressionCode = CSharpExpressionHelpers.TransformAttachedProperties(expressionCode); | |
| expressionCode = CSharpExpressionHelpers.ResolveXmlnsPrefixes(expressionCode, node.NamespaceResolver, Context); | |
| // Resolve xmlns prefixes first (e.g., local:Helper → fully qualified), then rewrite ABP syntax | |
| // (e.g., target.(Grid.Row) → Grid.GetRow(target)) so prefixed ABP types are recognized correctly. | |
| expressionCode = CSharpExpressionHelpers.ResolveXmlnsPrefixes(expressionCode, node.NamespaceResolver, Context); | |
| expressionCode = CSharpExpressionHelpers.TransformAttachedProperties(expressionCode); |
| // Pattern to match attached bindable property syntax: target.(Type.Property) or standalone (Type.Property) | ||
| static readonly Regex AttachedPropertyPattern = new Regex( | ||
| @"(?:(\w+)\.)?\(([A-Z]\w*)\.(\w+)\)", | ||
| RegexOptions.Compiled); |
There was a problem hiding this comment.
AttachedPropertyPattern only supports simple type identifiers (([A-Z]\w*)) and simple targets ((\w+)). This won’t handle the documented cases where the ABP type is qualified via xmlns prefix (ios:Page) or fully-qualified (Microsoft.Maui...Page), and it also won’t work if the type reference is expanded to global::... first. Consider parsing (Type.Property) by splitting on the last . inside the parentheses and allowing a broader Type grammar (including global::, namespaces, and prefix:Type).
| if (string.IsNullOrEmpty(target)) | ||
| { | ||
| // Standalone (Type.Prop) — source will be determined by expression analyzer | ||
| return $"{typeName}.Get{propertyName}(__source)"; | ||
| } |
There was a problem hiding this comment.
The standalone ABP rewrite emits __source ((Type.Prop) → Type.GetProp(__source)), but __source only exists in generated TypedBinding lambdas (i.e., when x:DataType is present). When an expression is used as a local initialization (no x:DataType), this will generate code that doesn’t compile. Consider either (1) only supporting the target.(Type.Prop) form in this preprocessing step, or (2) deferring the standalone (Type.Prop) handling until the binding-generation path where the source parameter is known.
| // Pattern to match xmlns prefix usage: prefix:TypeName (not at start of expression where it's a markup ext) | ||
| static readonly Regex XmlnsPrefixPattern = new Regex( | ||
| @"(?<![a-zA-Z0-9_])([a-zA-Z_]\w*):([A-Z]\w*)", | ||
| RegexOptions.Compiled); | ||
|
|
||
| /// <summary> | ||
| /// Resolves xmlns prefixes in expression code to fully qualified CLR type names. | ||
| /// E.g., "local:ExprHelper.GetValue()" → "Microsoft.Maui.Controls.Xaml.UnitTests.ExprHelper.GetValue()" | ||
| /// </summary> | ||
| public static string ResolveXmlnsPrefixes(string code, IXmlNamespaceResolver nsResolver, SourceGenContext context) | ||
| { | ||
| return XmlnsPrefixPattern.Replace(code, match => | ||
| { | ||
| var prefix = match.Groups[1].Value; | ||
| var typeName = match.Groups[2].Value; | ||
|
|
||
| // Skip the "x" prefix (x:Static, etc.) and known C# patterns | ||
| if (prefix == "x" || prefix == "global") | ||
| return match.Value; | ||
|
|
||
| var namespaceUri = nsResolver.LookupNamespace(prefix); | ||
| if (namespaceUri == null) | ||
| return match.Value; | ||
|
|
||
| // Resolve to CLR type | ||
| var xmlType = new XmlType(namespaceUri, typeName, null); | ||
| if (xmlType.TryResolveTypeSymbol(null, context.Compilation, context.XmlnsCache, context.TypeCache, out var typeSymbol)) | ||
| { | ||
| return $"global::{typeSymbol!.ContainingNamespace}.{typeName}"; | ||
| } |
There was a problem hiding this comment.
ResolveXmlnsPrefixes() does a regex replacement over raw expression text. This can rewrite occurrences inside string/char literals or the text portions of interpolated strings (e.g. $"literal local:Type"), changing runtime string values unexpectedly. Also, building the replacement with typeSymbol.ContainingNamespace + typeName can produce incorrect results for types in the global namespace or non-trivial type names; using the resolved typeSymbol’s fully-qualified display string (e.g. ToFQDisplayString() / FullyQualifiedFormat) is safer.
| | Code | Severity | Description | | ||
| |------|----------|-------------| | ||
| | MAUIX2018 | Error | `(Type.Property)`: Type could not be resolved via XAML namespaces | | ||
| | MAUIX2019 | Error | `(Type.Property)`: No attached BindableProperty `PropertyProperty` found on Type | | ||
| | MAUIX2020 | Error | `{(Type.Property)}` on BindingContext requires `x:DataType` to be a `BindableObject` | | ||
|
|
There was a problem hiding this comment.
The spec references diagnostics MAUIX2018/MAUIX2019/MAUIX2020, but these IDs don’t appear to be defined in the source generator’s Descriptors (only MAUIX2009–MAUIX2014 exist). Either add these diagnostics to the generator implementation (and ensure IDs are reserved/consistent), or update this section to reflect the actual diagnostics emitted for ABP failures.
| | Code | Severity | Description | | |
| |------|----------|-------------| | |
| | MAUIX2018 | Error | `(Type.Property)`: Type could not be resolved via XAML namespaces | | |
| | MAUIX2019 | Error | `(Type.Property)`: No attached BindableProperty `PropertyProperty` found on Type | | |
| | MAUIX2020 | Error | `{(Type.Property)}` on BindingContext requires `x:DataType` to be a `BindableObject` | | |
| ABP validation should report errors for the following cases, using the source generator's existing diagnostics for expression parsing and semantic resolution: | |
| | Scenario | Severity | Description | | |
| |----------|----------|-------------| | |
| | Unresolved type | Error | `(Type.Property)`: `Type` could not be resolved via XAML namespaces or using directives | | |
| | Missing attached property | Error | `(Type.Property)`: no attached `BindableProperty` named `PropertyProperty` (or matching `GetProperty`/`SetProperty` accessors) was found on `Type` | | |
| | Invalid BindingContext target | Error | `{(Type.Property)}` on `BindingContext` requires `x:DataType` to resolve to a `BindableObject` | |
| // XMLNS PREFIX IN EXPRESSIONS TESTS | ||
|
|
||
| [Fact] | ||
| public void XmlnsPrefixStaticMethodCall() | ||
| { | ||
| // {local:ExprHelper.GetStaticValue()} should resolve local: to CLR namespace | ||
| // and call the static method, not be treated as a markup extension | ||
| var page = new CSharpExpressions(XamlInflator.SourceGen); | ||
| Assert.Equal("Xmlns Prefix Value", page.xmlnsPrefixMethodLabel.Text); | ||
| } | ||
|
|
||
| // ATTACHED BINDABLE PROPERTY TESTS | ||
|
|
||
| [Fact] | ||
| public void AttachedProperty_FromNamedElement() | ||
| { | ||
| // {$'{gridChild.(Grid.Row)}'} should read Grid.Row from gridChild (which is set to 2) | ||
| var page = new CSharpExpressions(XamlInflator.SourceGen); | ||
| Assert.Equal("2", page.abpNamedElementLabel.Text); | ||
| } |
There was a problem hiding this comment.
Current tests cover local:ExprHelper.GetStaticValue() and a named-element ABP (gridChild.(Grid.Row)), but they don’t cover the interaction between the two new features (e.g. target.(ios:Type.Prop) / fully-qualified ABP type) or the standalone (Type.Prop) form described in the spec. Adding source-gen tests for those cases would help prevent regressions and validate the intended syntax/disambiguation rules.
This comment has been minimized.
This comment has been minimized.
MauiBot
left a comment
There was a problem hiding this comment.
Expert Review — 7 findings
See inline comments for details.
| var expressionCode = CSharpExpressionHelpers.GetExpressionCode(trimmed); | ||
| // Resolve xmlns prefixes (e.g., local:Helper → fully qualified) and ABP syntax (e.g., target.(Grid.Row) → Grid.GetRow(target)) | ||
| expressionCode = CSharpExpressionHelpers.TransformAttachedProperties(expressionCode); | ||
| expressionCode = CSharpExpressionHelpers.ResolveXmlnsPrefixes(expressionCode, node.NamespaceResolver, Context); |
There was a problem hiding this comment.
❌ Transform order is reversed. TransformAttachedProperties runs before ResolveXmlnsPrefixes, but the AttachedPropertyPattern regex ([A-Z]\w*)\.(\w+) cannot match prefixed type names like ios:Page because the colon is not in \w. The documented example this.(ios:Page.UseSafeArea) therefore silently falls through and emits broken code.
Fix: swap the two lines so xmlns prefixes are expanded first, then update AttachedPropertyPattern to accept fully-qualified names (post-expansion they look like global::Microsoft.Maui...Page). The same swap is needed at line 147-148 in the MarkupNode path.
| @"(?:(\w+)\.)?\(([A-Z]\w*)\.(\w+)\)", | ||
| RegexOptions.Compiled); | ||
|
|
||
| /// <summary> |
There was a problem hiding this comment.
❌ Wrong fully-qualified name builder. $"global::{typeSymbol.ContainingNamespace}.{typeName}" produces global::.Foo for types in the global namespace (because ContainingNamespace.ToString() returns "<global namespace>" or empty) and is incorrect for nested types. Use the existing helper instead:
return typeSymbol!.ToFQDisplayString();ISymbolExtensions.ToFQDisplayString() already wraps SymbolDisplayFormat.FullyQualifiedFormat and is used everywhere else in the source generator.
| { | ||
| var prefix = match.Groups[1].Value; | ||
| var typeName = match.Groups[2].Value; | ||
|
|
There was a problem hiding this comment.
XmlnsPrefixPattern will rewrite occurrences inside '...', "...", and the literal segments of $"..." interpolated strings. For example {$'open local:foo'} will silently rewrite the literal text. Same concern applies to AttachedPropertyPattern (e.g. {$'tuple is (Foo.Bar)'}).
Consider tokenizing the expression once and only rewriting identifier tokens, or use a regex that excludes content between matched quotes. At minimum, document the limitation and add a regression test covering string-literal cases.
| { | ||
| return AttachedPropertyPattern.Replace(code, match => | ||
| { | ||
| var target = match.Groups[1].Value; // "gridChild", "this", or empty |
There was a problem hiding this comment.
❌ AttachedPropertyPattern is too narrow to compose with the other features. The Type group is ([A-Z]\w*) — a single unqualified identifier. After this PR's own xmlns expansion, the type appears as global::Microsoft.Maui.Controls.PlatformConfiguration.iOSSpecific.Page, which the pattern cannot match. It also can't match XAML prefix forms (ios:Page) or fully-qualified paths a user might write directly.
Suggested grammar (split-on-last-dot inside parens):
@"(?:(\w+)\.)?\(((?:global::)?(?:[A-Za-z_]\w*(?:[:.]))*[A-Z]\w*)\.(\w+)\)"
or parse (X.Y) by finding the last . inside the parens and treating everything before it as the type expression.
| | MAUIX2018 | Error | `(Type.Property)`: Type could not be resolved via XAML namespaces | | ||
| | MAUIX2019 | Error | `(Type.Property)`: No attached BindableProperty `PropertyProperty` found on Type | | ||
| | MAUIX2020 | Error | `{(Type.Property)}` on BindingContext requires `x:DataType` to be a `BindableObject` | | ||
|
|
There was a problem hiding this comment.
src/Controls/src/SourceGen/Descriptors.cs (the highest existing ID is MAUIX2014) nor in AnalyzerReleases.Unshipped.md. Either:
- add the three new descriptors to
Descriptors.csandAnalyzerReleases.Unshipped.mdand emit them from the new code paths, or - rewrite this section to describe the diagnostics actually emitted (currently the new code is silent on bad ABP syntax — it just falls through to the C# compiler with a confusing error message).
Reserving IDs in the spec without implementing them creates a documentation/code drift the next contributor will hit.
| { | ||
| // {$'{gridChild.(Grid.Row)}'} should read Grid.Row from gridChild (which is set to 2) | ||
| var page = new CSharpExpressions(XamlInflator.SourceGen); | ||
| Assert.Equal("2", page.abpNamedElementLabel.Text); |
There was a problem hiding this comment.
💡 Test coverage gaps for the documented behaviors. The PR adds two features and tests one happy-path each. The spec promises significantly more:
this.(Grid.Row)from page roottarget.(ios:Page.UseSafeArea)— interaction between xmlns prefix and ABPmyBtn.(Grid.Row) * 100— ABP in compound expression- Standalone
{(Grid.Row)}from BindingContext (withx:DataTypeto aBindableObject) - Negative tests for the diagnostic IDs the spec advertises
Given the issues called out elsewhere in this review (regex narrowness, transform order, __source leak), several of these would currently fail and would have caught the bugs.
|
/review -b feature/refactor-copilot-yml |
MauiBot
left a comment
There was a problem hiding this comment.
Expert Review — 4 findings
See inline comments for details.
| /// </summary> | ||
| public static string TransformAttachedProperties(string code) | ||
| { | ||
| return AttachedPropertyPattern.Replace(code, match => |
There was a problem hiding this comment.
[major] XAML & Bindings — This regex rewrite runs over the entire expression text, including string/interpolated-string literals. A literal such as {value ?? '(Grid.Row)'} or $'Row (Grid.Row)' will have the text inside the string rewritten to Grid.GetRow(__source), changing the user-visible string. This needs a scanner/syntax-aware transform that skips literals and only lowers actual expression nodes.
|
|
||
| // Pattern to match attached bindable property syntax: target.(Type.Property) or standalone (Type.Property) | ||
| static readonly Regex AttachedPropertyPattern = new Regex( | ||
| @"(?:(\w+)\.)?\(([A-Z]\w*)\.(\w+)\)", |
There was a problem hiding this comment.
[major] XAML & Bindings — The ABP pattern only accepts (Type.Property) where Type starts with an uppercase identifier, so the documented prefixed form this.(ios:Page.UseSafeArea) is never lowered. Because ResolveXmlnsPrefixes runs after this transform, the expression becomes invalid C# with the parenthesized ABP syntax still present. Prefixed ABPs need to be resolved before/lowered by the ABP transform.
| if (string.IsNullOrEmpty(target)) | ||
| { | ||
| // Standalone (Type.Prop) — source will be determined by expression analyzer | ||
| return $"{typeName}.Get{propertyName}(__source)"; |
There was a problem hiding this comment.
[major] Logic and Correctness — Standalone ABP syntax is lowered to Grid.GetRow(__source), but __source only exists inside generated TypedBinding lambdas. For a local/non-typed expression like <Label Text="{(Grid.Row)}" />, this emits generated code that references an undefined variable. The transform needs to defer source selection to the binding analyzer or reject standalone ABP when no binding source exists.
|
|
||
| | Code | Severity | Description | | ||
| |------|----------|-------------| | ||
| | MAUIX2018 | Error | `(Type.Property)`: Type could not be resolved via XAML namespaces | |
There was a problem hiding this comment.
[moderate] Regression Prevention and Test Coverage — The spec documents MAUIX2018–MAUIX2020 diagnostics for invalid attached-property usage, but the PR does not add these descriptors or emit them; searching the SourceGen descriptors only shows existing MAUIX2007/2012/2013 diagnostics. Invalid ABP cases will therefore fall through to generated C# errors or incorrect rewrites instead of the promised diagnostics.
kubaflo
left a comment
There was a problem hiding this comment.
Could you check the ai's suggestions?
|
/review -b feature/enhanced-reviewer -p android |
kubaflo
left a comment
There was a problem hiding this comment.
Could you please check the ai's suggestions?
Make xmlns and attached bindable property preprocessing literal-aware, reject unsupported targetless ABP accesses without emitting __source, and align the C# expression spec with implemented behavior. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
6f14e74 to
c536147
Compare
| // If prefix:Name is followed by '.', it's a type reference in an expression | ||
| // (e.g., {local:Helper.GetValue()} or {this.(ios:Page.Prop)}), not a markup extension | ||
| if (end < trimmed.Length && trimmed[end] == '.') | ||
| return false; | ||
|
|
||
| // Otherwise, prefix:Name is a markup extension (custom or known) | ||
| return true; |
| foreach (var type in FindTypes(compilation.GlobalNamespace, metadataName)) | ||
| { | ||
| if (seen.Add(type)) | ||
| yield return type; | ||
| } |
| ### Diagnostics | ||
|
|
||
| There are no dedicated ABP-specific diagnostics yet. Invalid ABP expressions currently surface through existing source-generator diagnostics or generated C# compilation errors. |
MauiBot
left a comment
There was a problem hiding this comment.
AI Review Summary
@StephaneDelcroix — new AI review results are available based on this last commit:
c536147. To request a fresh review after new comments or commits, comment/review rerun.
🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix
Gate Result: ✅ PASSED
Platform: ANDROID · Base: main · Merge base: 657fb516
| Test | Without Fix (expect FAIL) | With Fix (expect PASS) |
|---|---|---|
🧪 CSharpExpressionDiagnosticsTests CSharpExpressionDiagnosticsTests |
✅ FAIL — 129s | ✅ PASS — 22s |
📄 CSharpExpressions.sgen CSharpExpressions.sgen |
🛠️ BUILD ERROR | 🔍 NO MATCH |
📄 UserInfo UserInfo |
🛠️ BUILD ERROR | 🔍 NO MATCH |
🔴 Without fix — 🧪 CSharpExpressionDiagnosticsTests: FAIL ✅ · 129s
Error-relevant lines (filtered from the build log):
at Microsoft.Maui.Controls.Xaml.UnitTests.SourceGen.SourceGeneratorDriver.RunGenerator[T](Compilation compilation, AdditionalFile[] additionalFiles, Boolean assertNoCompilationErrors) in /_/src/Controls/tests/SourceGen.UnitTests/SourceGeneratorDriver.cs:line 55
at Microsoft.Maui.Controls.Xaml.UnitTests.SourceGen.SourceGeneratorDriver.RunGenerator[T](Compilation compilation, AdditionalFile additionalFile, Boolean assertNoCompilationErrors) in /_/src/Controls/tests/SourceGen.UnitTests/SourceGeneratorDriver.cs:line 24
at Microsoft.Maui.Controls.SourceGen.UnitTests.SourceGenXamlInitializeComponentTestBase.RunGenerator(String xaml, String code, String noWarn, String targetFramework, String path, String lineinfo, Boolean assertNoCompilationErrors, Boolean enablePreviewFeatures) in /_/src/Controls/tests/SourceGen.UnitTests/InitializeComponent/SourceGenXamlInitializeComponentTests.cs:line 25
at Microsoft.Maui.Controls.SourceGen.UnitTests.CSharpExpressionDiagnosticsTests.AttachedBindableProperty_RewritesSkipStringAndInterpolatedLiteralSegments() in /_/src/Controls/tests/SourceGen.UnitTests/CSharpExpressionDiagnosticsTests.cs:line 969
at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
[xUnit.net 00:00:02.57] Collection: [Test.xaml(1,2): error MAUIG1001: An error occured while parsing Xaml: The given key 'Microsoft.Maui.Controls.Xaml.ElementNode' was not present in the dictionary..]
Collection: [Test.xaml(1,2): error MAUIG1001: An error occured while parsing Xaml: The given key 'Microsoft.Maui.Controls.Xaml.ElementNode' was not present in the dictionary..]
at Microsoft.Maui.Controls.SourceGen.UnitTests.CSharpExpressionDiagnosticsTests.XmlnsPrefix_TypeReference_UsesFullyQualifiedDisplayString() in /_/src/Controls/tests/SourceGen.UnitTests/CSharpExpressionDiagnosticsTests.cs:line 852
at Microsoft.Maui.Controls.SourceGen.UnitTests.CSharpExpressionDiagnosticsTests.AttachedBindableProperty_StandaloneTarget_IsRejectedWithoutSourceRewrite() in /_/src/Controls/tests/SourceGen.UnitTests/CSharpExpressionDiagnosticsTests.cs:line 1006
[xUnit.net 00:00:02.62] Collection: [Test.xaml(1,2): error MAUIG1001: An error occured while parsing Xaml: The given key 'Microsoft.Maui.Controls.Xaml.ElementNode' was not present in the dictionary..]
at Microsoft.Maui.Controls.SourceGen.UnitTests.CSharpExpressionDiagnosticsTests.AttachedBindableProperty_WithNamedTarget_RewritesToGetter() in /_/src/Controls/tests/SourceGen.UnitTests/CSharpExpressionDiagnosticsTests.cs:line 890
at Microsoft.Maui.Controls.SourceGen.UnitTests.CSharpExpressionDiagnosticsTests.AttachedBindableProperty_WithXmlnsPrefix_RewritesToFullyQualifiedGetter() in /_/src/Controls/tests/SourceGen.UnitTests/CSharpExpressionDiagnosticsTests.cs:line 923
🟢 With fix — 🧪 CSharpExpressionDiagnosticsTests: PASS ✅ · 22s
(no coded error found; showing last 1200 chars)
eGen.UnitTests.CSharpExpressionDiagnosticsTests.AttachedBindableProperty_StandaloneTarget_IsRejectedWithoutSourceRewrite [16 ms]
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.CSharpExpressionDiagnosticsTests.ComplexExpression_OnTwoWayProperty_EmitsInfoDiagnostic [16 ms]
[xUnit.net 00:00:05.25] Finished: Microsoft.Maui.Controls.SourceGen.UnitTests
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.CSharpExpressionDiagnosticsTests.AttachedBindableProperty_WithNamedTarget_RewritesToGetter [45 ms]
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.CSharpExpressionDiagnosticsTests.SingleQuotedLiteral_MethodExpectsString_GeneratesStringLiteral [30 ms]
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.CSharpExpressionDiagnosticsTests.BareIdentifier_ExplicitExpressionSyntax_NoAmbiguityWarning [26 ms]
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.CSharpExpressionDiagnosticsTests.AttachedBindableProperty_WithXmlnsPrefix_RewritesToFullyQualifiedGetter [33 ms]
Passed Microsoft.Maui.Controls.SourceGen.UnitTests.CSharpExpressionDiagnosticsTests.ExplicitDotPrefix_NoAmbiguousError [27 ms]
Test Run Successful.
Total tests: 24
Passed: 24
Total time: 6.4416 Seconds
🔴 Without fix — 📄 CSharpExpressions.sgen: 🛠️ BUILD ERROR · 60s
Error-relevant lines (filtered from the build log):
/home/vsts/work/1/s/src/Controls/tests/Xaml.UnitTests/CSharpExpressions.sgen.xaml(1,2): error MAUIG1001: An error occured while parsing Xaml: The given key 'Microsoft.Maui.Controls.Xaml.ElementNode' was not present in the dictionary.. [/home/vsts/work/1/s/src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/Xaml.UnitTests/Generated/Microsoft.Maui.Controls.SourceGen/Microsoft.Maui.Controls.SourceGen.XamlGenerator/CSharpExpressions.sgen.xaml.sg.cs(353,24): error CS8795: Partial method 'CSharpExpressions.InitializeComponentSourceGen()' must have an implementation part because it has accessibility modifiers. [/home/vsts/work/1/s/src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj]
🟢 With fix — 📄 CSharpExpressions.sgen: 🔍 NO MATCH · 63s
(no coded error found; showing last 1200 chars)
ps://learn.microsoft.com/dotnet/maui/fundamentals/data-binding/compiled-bindings for more information. [/home/vsts/work/1/s/src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj]
Controls.Xaml.UnitTests -> /home/vsts/work/1/s/artifacts/bin/Controls.Xaml.UnitTests/Debug/net10.0/Microsoft.Maui.Controls.Xaml.UnitTests.dll
Test run for /home/vsts/work/1/s/artifacts/bin/Controls.Xaml.UnitTests/Debug/net10.0/Microsoft.Maui.Controls.Xaml.UnitTests.dll (.NETCoreApp,Version=v10.0)
VSTest version 18.0.1 (x64)
Starting test execution, please wait...
A total of 1 test files matched the specified pattern.
[xUnit.net 00:00:00.00] xUnit.net VSTest Adapter v2.8.2+699d445a1a (64-bit .NET 10.0.0)
[xUnit.net 00:00:00.31] Discovering: Microsoft.Maui.Controls.Xaml.UnitTests
[xUnit.net 00:00:04.60] Discovered: Microsoft.Maui.Controls.Xaml.UnitTests
[xUnit.net 00:00:04.61] Starting: Microsoft.Maui.Controls.Xaml.UnitTests
[xUnit.net 00:00:04.63] Finished: Microsoft.Maui.Controls.Xaml.UnitTests
No test matches the given testcase filter `CSharpExpressions.sgen` in /home/vsts/work/1/s/artifacts/bin/Controls.Xaml.UnitTests/Debug/net10.0/Microsoft.Maui.Controls.Xaml.UnitTests.dll
🔴 Without fix — 📄 UserInfo: 🛠️ BUILD ERROR · 31s
Error-relevant lines (filtered from the build log):
/home/vsts/work/1/s/src/Controls/tests/Xaml.UnitTests/CSharpExpressions.sgen.xaml(1,2): error MAUIG1001: An error occured while parsing Xaml: The given key 'Microsoft.Maui.Controls.Xaml.ElementNode' was not present in the dictionary.. [/home/vsts/work/1/s/src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj]
/home/vsts/work/1/s/src/Controls/tests/Xaml.UnitTests/Generated/Microsoft.Maui.Controls.SourceGen/Microsoft.Maui.Controls.SourceGen.XamlGenerator/CSharpExpressions.sgen.xaml.sg.cs(353,24): error CS8795: Partial method 'CSharpExpressions.InitializeComponentSourceGen()' must have an implementation part because it has accessibility modifiers. [/home/vsts/work/1/s/src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj]
🟢 With fix — 📄 UserInfo: 🔍 NO MATCH · 23s
(no coded error found; showing last 1200 chars)
dll
##vso[build.updatebuildnumber]10.0.100-ci+azdo.14740392
Controls.Build.Tasks -> /home/vsts/work/1/s/artifacts/bin/Controls.Build.Tasks/Debug/netstandard2.0/Microsoft.Maui.Controls.Build.Tasks.dll
Controls.Xaml.UnitTests -> /home/vsts/work/1/s/artifacts/bin/Controls.Xaml.UnitTests/Debug/net10.0/Microsoft.Maui.Controls.Xaml.UnitTests.dll
Test run for /home/vsts/work/1/s/artifacts/bin/Controls.Xaml.UnitTests/Debug/net10.0/Microsoft.Maui.Controls.Xaml.UnitTests.dll (.NETCoreApp,Version=v10.0)
VSTest version 18.0.1 (x64)
Starting test execution, please wait...
A total of 1 test files matched the specified pattern.
[xUnit.net 00:00:00.00] xUnit.net VSTest Adapter v2.8.2+699d445a1a (64-bit .NET 10.0.0)
[xUnit.net 00:00:00.31] Discovering: Microsoft.Maui.Controls.Xaml.UnitTests
[xUnit.net 00:00:06.85] Discovered: Microsoft.Maui.Controls.Xaml.UnitTests
[xUnit.net 00:00:06.86] Starting: Microsoft.Maui.Controls.Xaml.UnitTests
[xUnit.net 00:00:06.88] Finished: Microsoft.Maui.Controls.Xaml.UnitTests
No test matches the given testcase filter `UserInfo` in /home/vsts/work/1/s/artifacts/bin/Controls.Xaml.UnitTests/Debug/net10.0/Microsoft.Maui.Controls.Xaml.UnitTests.dll
⚠️ Failure Details
- 🛠️ CSharpExpressions.sgen without fix: build failed before tests could run
/home/vsts/work/1/s/src/Controls/tests/Xaml.UnitTests/CSharpExpressions.sgen.xaml(1,2): error MAUIG1001: An error occured while parsing Xaml: The given key 'Microsoft.Maui.Controls.Xaml.ElementNode' w...
- 🛠️ UserInfo without fix: build failed before tests could run
/home/vsts/work/1/s/src/Controls/tests/Xaml.UnitTests/CSharpExpressions.sgen.xaml(1,2): error MAUIG1001: An error occured while parsing Xaml: The given key 'Microsoft.Maui.Controls.Xaml.ElementNode' w...
- 🔍 CSharpExpressions.sgen with fix: test filter matched 0 tests
- filter:
CSharpExpressions.sgen
- filter:
- 🔍 UserInfo with fix: test filter matched 0 tests
- filter:
UserInfo
- filter:
📁 Fix files reverted (2 files)
src/Controls/src/SourceGen/CSharpExpressionHelpers.cssrc/Controls/src/SourceGen/Visitors/ExpandMarkupsVisitor.cs
📱 UI Tests — Button,Label,Layout
Detected UI test categories: Button,Label,Layout
✅ Deep UI tests — 366 passed, 0 failed across 3 categories on platform-pool agent (replaces in-process counts above).
🧪 UI Test Execution Results (deep, platform pool)
| Category | Tests | Snapshot diffs |
|---|---|---|
Button |
71/73 ✓ | — |
Label |
96/98 ✓ | — |
Layout |
199/202 ✓ | — |
📎 Download drop-deep-uitests artifact (TRX + snapshot diffs) |
📋 Pre-Flight — Context & Validation
Issue: N/A - feature PR without linked issue
PR: #35007 - Support xmlns prefixes and attached bindable properties in C# expressions
Platforms Affected: Source generator / XAML C# expressions (platform-independent; tested with source-generator unit tests, Android requested but no Android-specific code path)
Files Changed: 2 implementation, 2 test, 1 docs/spec
Key Findings
- PR adds XML namespace type references in XAML C# expressions, plus
target.(Type.Property)attached bindable property reads. - Prior gate result supplied by caller: Gate ✅ PASSED — tests fail without the PR fix and pass with it. Gate was not rerun.
ghis unauthenticated in this environment; PR/issue context was gathered from the local PR branch and public REST API output.- Prior review comments flagged unresolved risks around named-argument rewriting and typed-binding handler generation for ABP compound expressions.
Code Review Summary
Verdict: NEEDS_CHANGES
Confidence: low
Errors: 2 | Warnings: 0 | Suggestions: 0
Key code review findings:
- ✗
src/Controls/src/SourceGen/CSharpExpressionHelpers.cs: XML namespace prefix rewrite can corrupt valid C# named arguments such asFormat(local:Helper). - ✗
src/Controls/src/SourceGen/CSharpExpressionHelpers.cs/ typed-binding flow: ABP lowering toGrid.GetRow(button)can be misread asx:DataTypemember access and produce invalid__source.Gridhandlers.
Fix Candidates
| # | Source | Approach | Test Result | Files Changed | Notes |
|---|---|---|---|---|---|
| PR | PR #35007 | Regex-based xmlns prefix replacement + textual ABP rewrite before expression nodes are emitted | ✅ PASSED (Gate supplied by caller) | CSharpExpressionHelpers.cs, ExpandMarkupsVisitor.cs, tests, docs |
Original PR fix; review found two correctness risks to explore alternatives for |
🔬 Code Review — Deep Analysis
Code Review — PR #35007
Independent Assessment
What this changes: Adds XAML C# expression preprocessing for xmlns type references and target.(Type.Property) attached-property reads.
Inferred motivation: Let source-generated C# expressions use XAML namespace aliases and attached bindable properties.
Reconciliation with PR Narrative
Author claims: Adds prefix:Type references, target-qualified ABP reads, docs, and tests.
Agreement/disagreement: Mostly matches, but there are still correctness holes in valid C# named-argument syntax and ABP compound typed-binding scenarios.
Prior Review Reconciliation
| Prior ❌ Error Finding | Source | Status | Evidence |
|---|---|---|---|
| Transform order reversed | MauiBot | ✅ Fixed | ExpandMarkupsVisitor.cs:77-81, 148-152 resolve xmlns before ABP rewrite. |
| FQ name builder broken | MauiBot | ✅ Fixed | CSharpExpressionHelpers.cs:916 uses ToFQDisplayString(). |
| ABP pattern too narrow | MauiBot | ✅ Fixed | CSharpExpressionHelpers.cs:925 supports global:: and dotted type names. |
Standalone __source leak |
MauiBot | ✅ Fixed | Empty target returns unchanged at CSharpExpressionHelpers.cs:956-957; diagnostic path at ExpandMarkupsVisitor.cs:217-227. |
| Prefix rewrite corrupts valid named-argument syntax | MauiBot | ❌ Unresolved | XmlnsPrefixPattern still blindly rewrites prefix:TypeName outside literals at CSharpExpressionHelpers.cs:890/899. |
Blast Radius Assessment
- Runs for all instances: No; only source-generator expression preprocessing.
- Startup impact: No runtime startup impact, but can break build output.
- Static/shared state: No.
- Scope: Shared XAML source-generator path; max confidence would be medium, then CI tool availability caps lower.
CI Status
- Required-check result: undetermined —
gh pr checks 35007 --requiredfailed with auth error. - Classification: tool unavailable; public check-runs API showed current
maui-prsuccess, but not required-check status. - Action taken: capped confidence; did not infer clean required CI.
Findings
❌ Error — xmlns prefix rewrite can corrupt valid C# named arguments
src/Controls/src/SourceGen/CSharpExpressionHelpers.cs:890 / :899
The regex still rewrites every prefix:TypeName outside literals when the prefix resolves as an XML namespace. That also matches valid C# named-argument syntax such as DoSomething(local:Bar). If xmlns:local exists and Bar resolves as a type, the generated expression becomes DoSomething(global::SomeNamespace.Bar), changing or breaking valid C#.
❌ Error — ABP compound expressions can generate invalid typed-binding handlers
src/Controls/src/SourceGen/CSharpExpressionHelpers.cs:962
Lowering button.(Grid.Row) to Grid.GetRow(button) introduces a static member access into expressions that may also reference x:DataType properties, e.g. {button.(Grid.Row) + Price}. The typed-binding analyzer treats Grid.GetRow as a property chain and can emit handler code like static __source => __source.Grid, which fails because the view model has no Grid property. The docs explicitly advertise compound ABP expressions, but tests don’t cover the x:DataType mixed case.
Failure-Mode Probing
- Valid named argument with matching XML prefix: incorrectly rewritten.
- ABP inside
x:DataTypecompound expression: likely invalid generated handler code. - String/interpolated literals: fixed via literal-span scanning.
Verdict: NEEDS_CHANGES
Confidence: low, capped because required CI could not be queried with gh.
Summary: Several earlier issues were fixed, but one prior ❌ remains unresolved and another build-breaking ABP composition case was found. No GitHub comments were posted.
🛠️ Fix — Analysis & Comparison
Fix Candidates
| # | Source | Approach | Test Result | Files Changed | Notes |
|---|---|---|---|---|---|
| 1 | try-fix | Syntax-aware prefix lowering plus typed-binding handler filtering | ✅ PASS | 4 files | Handles no-space named arguments and prevents __source.Grid handler generation for ABP static getter calls |
| PR | PR #35007 | Regex-based xmlns prefix replacement + textual ABP rewrite | ✅ PASSED (Gate) | 2 implementation files + tests/docs | Original PR; gate passed but code review found unaddressed edge cases |
Cross-Pollination
| Model | Round | New Ideas? | Details |
|---|---|---|---|
| maui-expert-reviewer | 1 | Yes | Proposed syntax-aware lowering and binding-analysis exclusions/filtering; implemented as candidate #1 |
Exhausted: No — stopped because candidate #1 passed the targeted regression suite and is demonstrably better than the PR fix for the reviewed edge cases.
Selected Fix: Candidate #1 — It preserves the PR feature while adding discriminating safeguards for valid C# named arguments and typed-binding ABP compound expressions.
📝 Recommended PR Title & Description
Assessment: ✏️ Recommend updating — the winning fix adds named-argument protection and typed-binding handler filtering that the current title/description do not mention.
Recommended title
XAML SourceGen: Support xmlns prefixes and attached bindable properties in C# expressions
Recommended description
## Description
Adds two new capabilities to the XAML C# expression source generator and hardens the generated-code analysis for edge cases found during review.
### 1. xmlns prefix type references in expressions
Expressions can now reference types via XAML xmlns prefixes. The prefix is resolved to the fully qualified CLR type name before compilation.
```xml
<ContentPage xmlns:local="clr-namespace:MyApp.Helpers">
<Label Text="{local:Helper.GetValue()}" />
</ContentPage>
Previously, {local:Helper.GetValue()} was incorrectly classified as a markup extension because the prefix:Name pattern was always treated as markup. Now, prefix:Name. (followed by .) is recognized as a type reference in an expression.
The implementation also avoids rewriting valid C# named-argument syntax such as Format(local: value) or Format(local:ExpressionHelper) when an xmlns prefix with the same name exists.
2. Attached Bindable Property (ABP) syntax
Expressions support (Type.Property) syntax for reading attached properties, following the x:Bind convention.
<Grid>
<Button x:Name="myBtn" Grid.Row="2" />
<Label Text="{$'Row {myBtn.(Grid.Row)}'}" />
</Grid>The source generator transforms target.(Type.Property) into Type.GetProperty(target) calls. For typed-binding compound expressions, generated handler analysis filters out source-generator-introduced static type roots so ABP calls such as Grid.GetRow(myBtn) do not produce invalid handlers like __source.Grid.
3. Spec update
Updated docs/specs/XamlCSharpExpressions.md with:
- New Attached Bindable Properties section with syntax, examples, disambiguation rules, and diagnostics
- New Type References section explaining xmlns prefix usage in expressions
Changes
| File | Change |
|---|---|
CSharpExpressionHelpers.cs |
StartsWithMarkupExtension fix for prefix:Type. + ResolveXmlnsPrefixes() + TransformAttachedProperties(); preserves named arguments and validates standalone ABP syntax |
ExpandMarkupsVisitor.cs |
Wires preprocessing into both ValueNode and MarkupNode expression paths |
ExpressionAnalyzer.cs |
Filters typed-binding handlers so ABP-generated static getter calls do not create invalid data-type member handlers |
XamlCSharpExpressions.md |
Spec: ABP section, Type References section |
CSharpExpressionDiagnosticsTests.cs and CSharpExpressions.sgen.xaml[.cs] |
Tests for xmlns prefix references, ABP access, literal skipping, standalone ABP diagnostics, named-argument preservation, and typed-binding ABP compound expressions |
Platforms Tested
- Android
</details>
---
<details>
<summary><strong>🏁 Report — Final Recommendation</strong></summary>
<br/>
## Comparative Fix Report — PR #35007
### Candidates compared
| Candidate | Source | Regression result | Assessment |
|---|---|---:|---|
| `pr` | Raw PR #35007 fix | ✅ Passed supplied gate | Adds xmlns prefix type references and ABP syntax, with tests and docs. However, STEP 5a review found remaining correctness risks: resolvable `prefix:Type` tokens can be rewritten inside valid C# named arguments, and ABP lowering can confuse typed-binding handler generation in compound `x:DataType` expressions. |
| `pr-plus-reviewer` | PR plus current MAUI expert reviewer feedback | ✅ Same as `pr` | The expert reviewer produced `[]`, so there were no actionable edits to apply. This candidate is equivalent to the raw PR and inherits the same edge-case risks. |
| `try-fix-1` | STEP 5a try-fix candidate | ✅ Passed targeted regression suite | Preserves the PR feature while adding two safeguards: prefix lowering only happens for type-reference syntax followed by `.`, and typed-binding nested handlers are filtered so source-generator-created static calls do not emit invalid roots like `__source.Grid`. It also expands regression coverage for named arguments and typed ABP compound expressions. |
### Ranking
1. `try-fix-1` — Best overall. It passed regression testing and directly addresses the two correctness issues identified during review while preserving the PR's intended feature set.
2. `pr-plus-reviewer` — Tied with `pr` functionally because no reviewer edits were produced; ranked above `pr` only as the explicitly evaluated expert-reviewer candidate.
3. `pr` — Passed the supplied gate, but is less robust because it lacks STEP 5a's named-argument and typed-binding safeguards.
### Winning candidate
`try-fix-1` is the single winning candidate. It is not the PR fix as submitted, so the winner manifest includes the candidate's unified diff against PR base.
### Rationale
All candidates with available results passed their regression tests, so the decision turns on correctness coverage and residual risk. `try-fix-1` strictly improves the PR approach by keeping the intended xmlns/ABP behavior and adding targeted protection for valid C# named arguments and typed-binding ABP compound expressions, both of which can affect generated-code correctness.
</details>
</details>
<!-- SESSION:c536147 END -->
---
<details>
<summary><strong>🧭 Next Steps</strong> — alternative fix proposed (<code>try-fix-1</code>)</summary>
<br/>
**Automated review — alternative fix proposed**
The expert-reviewer evaluation compared the PR fix against automatically generated candidates and selected <code>try-fix-1</code> as the strongest fix.
**Why:** try-fix-1 passed the targeted regression suite and preserves the PR feature while fixing the named-argument rewrite and typed-binding ABP handler risks found in STEP 5a. The expert-reviewer pass produced no additional PR edits, so pr-plus-reviewer is equivalent to the raw PR and ranks lower.
Please consider applying the candidate diff below (or use it as guidance). Once you push an update, this workflow will re-trigger and re-evaluate.
<details><summary>Candidate diff (<code>try-fix-1</code>)</summary>
````diff
diff --git a/src/Controls/src/SourceGen/CSharpExpressionHelpers.cs b/src/Controls/src/SourceGen/CSharpExpressionHelpers.cs
index 9d973b0058..a0a676f540 100644
--- a/src/Controls/src/SourceGen/CSharpExpressionHelpers.cs
+++ b/src/Controls/src/SourceGen/CSharpExpressionHelpers.cs
@@ -3,9 +3,11 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
+using System.Xml;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.Maui.Controls.Xaml;
namespace Microsoft.Maui.Controls.SourceGen;
@@ -35,6 +37,7 @@ static class CSharpExpressionHelpers
@"|\s*\.[A-Za-z_]" + // Dot prefix for binding: {.Name
@"|\s*this\." + // this. prefix for local: {this.Foo
@"|\s*BindingContext\." + // BindingContext. prefix for binding: {BindingContext.Foo
+ @"|\s*[A-Za-z_]\w*\.\(" + // Attached BP target syntax: {target.(Grid.Row)
@")",
RegexOptions.Compiled);
@@ -181,8 +184,12 @@ static class CSharpExpressionHelpers
var colonIndex = identifier.IndexOf(':');
if (colonIndex >= 0)
{
- // Any prefix:Name pattern is a markup extension (custom or known)
- // C# doesn't use this syntax, so it's safe to treat as markup
+ // If prefix:Name is followed by '.', it's a type reference in an expression
+ // (e.g., {local:Helper.GetValue()} or {this.(ios:Page.Prop)}), not a markup extension
+ if (end < trimmed.Length && trimmed[end] == '.')
+ return false;
+
+ // Otherwise, prefix:Name is a markup extension (custom or known)
return true;
}
@@ -889,4 +896,314 @@ static class CSharpExpressionHelpers
// Use same extraction as expressions
return GetExpressionCode(value);
}
+
+ // Pattern to match xmlns prefix usage: prefix:TypeName (not at start of expression where it's a markup ext)
+ static readonly Regex XmlnsPrefixPattern = new Regex(
+ @"(?<![a-zA-Z0-9_])([a-zA-Z_]\w*):([A-Z]\w*)",
+ RegexOptions.Compiled);
+
+ /// <summary>
+ /// Resolves xmlns prefixes in expression code to fully qualified CLR type names.
+ /// E.g., "local:ExprHelper.GetValue()" → "Microsoft.Maui.Controls.Xaml.UnitTests.ExprHelper.GetValue()"
+ /// </summary>
+ public static string ResolveXmlnsPrefixes(string code, IXmlNamespaceResolver nsResolver, SourceGenContext context)
+ {
+ return ReplaceOutsideLiteralSegments(code, XmlnsPrefixPattern, match =>
+ {
+ if (match.Index + match.Length >= code.Length || code[match.Index + match.Length] != '.')
+ return match.Value;
+
+ var prefix = match.Groups[1].Value;
+ var typeName = match.Groups[2].Value;
+
+ // Skip the "x" prefix (x:Static, etc.) and known C# patterns
+ if (prefix == "x" || prefix == "global")
+ return match.Value;
+
+ var namespaceUri = nsResolver.LookupNamespace(prefix);
+ if (namespaceUri == null)
+ return match.Value;
+
+ // Resolve to CLR type
+ var xmlType = new XmlType(namespaceUri, typeName, null);
+ if (xmlType.TryResolveTypeSymbol(null, context.Compilation, context.XmlnsCache, context.TypeCache, out var typeSymbol))
+ {
+ return typeSymbol!.ToFQDisplayString();
+ }
+
+ return match.Value;
+ });
+ }
+
+ // Pattern to match attached bindable property syntax: target.(Type.Property) or standalone (Type.Property)
+ static readonly Regex AttachedPropertyPattern = new Regex(
+ @"(?:(?<target>[A-Za-z_]\w*)\.)?\((?<member>(?:global::)?[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)+)\)",
+ RegexOptions.Compiled);
+
+ public static bool TryGetStandaloneAttachedProperty(string code, Compilation compilation, out string attachedProperty)
+ {
+ foreach (Match match in MatchesOutsideLiteralSegments(code, AttachedPropertyPattern))
+ {
+ if (!match.Groups["target"].Success
+ && IsAttachedProperty(match.Groups["member"].Value, compilation))
+ {
+ attachedProperty = match.Value;
+ return true;
+ }
+ }
+
+ attachedProperty = string.Empty;
+ return false;
+ }
+
+ /// <summary>
+ /// Transforms attached bindable property syntax to static Get method calls.
+ /// E.g., "gridChild.(Grid.Row)" → "Grid.GetRow(gridChild)"
+ /// E.g., "this.(Grid.Row)" → "Grid.GetRow(this)"
+ /// </summary>
+ public static string TransformAttachedProperties(string code, Compilation compilation)
+ {
+ return ReplaceOutsideLiteralSegments(code, AttachedPropertyPattern, match =>
+ {
+ var target = match.Groups["target"].Value; // "gridChild", "this", or empty
+ var member = match.Groups["member"].Value; // "Grid.Row" or "global::Namespace.Grid.Row"
+
+ if (string.IsNullOrEmpty(target))
+ return match.Value;
+
+ if (!TrySplitAttachedProperty(member, out var typeName, out var propertyName))
+ return match.Value;
+
+ typeName = StripGlobalAlias(ResolveTypeSymbols(typeName, compilation).FirstOrDefault()?.ToFQDisplayString() ?? typeName);
+
+ return $"{typeName}.Get{propertyName}({target})";
+ });
+ }
+
+ static string StripGlobalAlias(string typeName)
+ {
+ return typeName.StartsWith("global::", StringComparison.Ordinal)
+ ? typeName.Substring("global::".Length)
+ : typeName;
+ }
+
+ static bool TrySplitAttachedProperty(string member, out string typeName, out string propertyName)
+ {
+ typeName = string.Empty;
+ propertyName = string.Empty;
+
+ var lastDot = member.LastIndexOf('.');
+ if (lastDot <= 0 || lastDot == member.Length - 1)
+ return false;
+
+ typeName = member.Substring(0, lastDot);
+ propertyName = member.Substring(lastDot + 1);
+
+ if (!IsIdentifier(propertyName) || !LooksLikeTypeName(typeName))
+ return false;
+
+ return true;
+ }
+
+ static bool IsAttachedProperty(string member, Compilation compilation)
+ {
+ if (!TrySplitAttachedProperty(member, out var typeName, out var propertyName))
+ return false;
+
+ foreach (var type in ResolveTypeSymbols(typeName, compilation))
+ {
+ if (HasAttachedProperty(type, propertyName, compilation))
+ return true;
+ }
+
+ return false;
+ }
+
+ static IEnumerable<INamedTypeSymbol> ResolveTypeSymbols(string typeName, Compilation compilation)
+ {
+ var metadataName = typeName.StartsWith("global::", StringComparison.Ordinal)
+ ? typeName.Substring("global::".Length)
+ : typeName;
+ var seen = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default);
+ var foundDirectMatch = false;
+
+ foreach (var type in compilation.GetTypesByMetadataName(metadataName).OfType<INamedTypeSymbol>())
+ {
+ foundDirectMatch = true;
+ if (seen.Add(type))
+ yield return type;
+ }
+
+ if (foundDirectMatch)
+ yield break;
+
+ foreach (var type in FindTypes(compilation.GlobalNamespace, metadataName))
+ {
+ if (seen.Add(type))
+ yield return type;
+ }
+ }
+
+ static IEnumerable<INamedTypeSymbol> FindTypes(INamespaceSymbol namespaceSymbol, string metadataName)
+ {
+ foreach (var nestedNamespace in namespaceSymbol.GetNamespaceMembers())
+ {
+ foreach (var type in FindTypes(nestedNamespace, metadataName))
+ yield return type;
+ }
+
+ foreach (var type in namespaceSymbol.GetTypeMembers())
+ {
+ foreach (var candidate in FindTypes(type, metadataName))
+ yield return candidate;
+ }
+ }
+
+ static IEnumerable<INamedTypeSymbol> FindTypes(INamedTypeSymbol typeSymbol, string metadataName)
+ {
+ if (typeSymbol.Name == metadataName
+ || typeSymbol.ToFQDisplayString() == $"global::{metadataName}")
+ {
+ yield return typeSymbol;
+ }
+
+ foreach (var nestedType in typeSymbol.GetTypeMembers())
+ {
+ foreach (var candidate in FindTypes(nestedType, metadataName))
+ yield return candidate;
+ }
+ }
+
+ static bool HasAttachedProperty(INamedTypeSymbol type, string propertyName, Compilation compilation)
+ {
+ var bindablePropertyType = compilation.GetTypeByMetadataName("Microsoft.Maui.Controls.BindableProperty");
+ var bindablePropertyName = $"{propertyName}Property";
+
+ foreach (var member in type.GetMembers(bindablePropertyName))
+ {
+ if (member is IFieldSymbol field
+ && field.IsStatic
+ && (bindablePropertyType is null || SymbolEqualityComparer.Default.Equals(field.Type, bindablePropertyType)))
+ {
+ return true;
+ }
+ }
+
+ var getterName = $"Get{propertyName}";
+ foreach (var member in type.GetMembers(getterName))
+ {
+ if (member is IMethodSymbol method
+ && method.IsStatic
+ && method.Parameters.Length == 1
+ && method.ReturnsVoid == false)
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ static bool LooksLikeTypeName(string typeName)
+ {
+ var candidate = typeName.StartsWith("global::", StringComparison.Ordinal)
+ ? typeName.Substring("global::".Length)
+ : typeName;
+
+ var lastDot = candidate.LastIndexOf('.');
+ var typeSegment = lastDot >= 0 ? candidate.Substring(lastDot + 1) : candidate;
+
+ return typeSegment.Length > 0 && char.IsUpper(typeSegment[0]);
+ }
+
+ static bool IsIdentifier(string value)
+ {
+ if (string.IsNullOrEmpty(value) || !(char.IsLetter(value[0]) || value[0] == '_'))
+ return false;
+
+ for (var i = 1; i < value.Length; i++)
+ {
+ if (!(char.IsLetterOrDigit(value[i]) || value[i] == '_'))
+ return false;
+ }
+
+ return true;
+ }
+
+ static string ReplaceOutsideLiteralSegments(string code, Regex pattern, MatchEvaluator evaluator)
+ {
+ var matches = pattern.Matches(code).Cast<Match>().ToArray();
+ if (matches.Length == 0)
+ return code;
+
+ var literalSpans = GetLiteralSegmentSpans(code);
+ var result = new StringBuilder(code.Length);
+ var currentIndex = 0;
+
+ foreach (var match in matches)
+ {
+ if (OverlapsLiteralSegment(match.Index, match.Length, literalSpans))
+ continue;
+
+ result.Append(code, currentIndex, match.Index - currentIndex);
+ result.Append(evaluator(match));
+ currentIndex = match.Index + match.Length;
+ }
+
+ result.Append(code, currentIndex, code.Length - currentIndex);
+ return result.ToString();
+ }
+
+ static IEnumerable<Match> MatchesOutsideLiteralSegments(string code, Regex pattern)
+ {
+ var matches = pattern.Matches(code).Cast<Match>().ToArray();
+ if (matches.Length == 0)
+ yield break;
+
+ var literalSpans = GetLiteralSegmentSpans(code);
+
+ foreach (var match in matches)
+ {
+ if (!OverlapsLiteralSegment(match.Index, match.Length, literalSpans))
+ yield return match;
+ }
+ }
+
+ static List<(int Start, int End)> GetLiteralSegmentSpans(string code)
+ {
+ var tree = CSharpSyntaxTree.ParseText(code, new CSharpParseOptions(kind: SourceCodeKind.Script));
+ var root = tree.GetRoot();
+ var spans = new List<(int Start, int End)>();
+
+ foreach (var token in root.DescendantTokens(descendIntoTrivia: true))
+ {
+ if (!IsLiteralSegmentToken(token))
+ continue;
+
+ spans.Add((token.SpanStart, token.Span.End));
+ }
+
+ return spans;
+ }
+
+ static bool IsLiteralSegmentToken(SyntaxToken token)
+ {
+ var kind = token.Kind().ToString();
+ return kind.Contains("StringLiteralToken", StringComparison.Ordinal)
+ || kind.Contains("CharacterLiteralToken", StringComparison.Ordinal)
+ || kind.Equals("InterpolatedStringTextToken", StringComparison.Ordinal)
+ || kind.Equals("InterpolatedRawStringTextToken", StringComparison.Ordinal);
+ }
+
+ static bool OverlapsLiteralSegment(int start, int length, List<(int Start, int End)> literalSpans)
+ {
+ var end = start + length;
+ foreach (var span in literalSpans)
+ {
+ if (start < span.End && end > span.Start)
+ return true;
+ }
+
+ return false;
+ }
}
diff --git a/src/Controls/src/SourceGen/ExpressionAnalyzer.cs b/src/Controls/src/SourceGen/ExpressionAnalyzer.cs
index b97dd186a1..a95bbf5fdf 100644
--- a/src/Controls/src/SourceGen/ExpressionAnalyzer.cs
+++ b/src/Controls/src/SourceGen/ExpressionAnalyzer.cs
@@ -335,7 +335,8 @@ internal static class ExpressionAnalyzer
handlers = handlers.Where(h =>
h.PropertyName == "." ||
(h.ParentExpression != sourceParameterName && // Keep nested handlers...
- !h.ParentExpression.Contains("__capture_")) || // ...unless parent is a capture variable
+ !h.ParentExpression.Contains("__capture_") && // ...unless parent is a capture variable
+ HandlerRootExistsOnDataType(h.ParentExpression, sourceParameterName, dataType)) ||
HasProperty(dataType, h.PropertyName) // Top-level must exist on DataType
).ToList();
}
@@ -353,6 +354,19 @@ internal static class ExpressionAnalyzer
return new ExpressionAnalysisResult(handlers, captures, transformedExpression, isSettable);
}
+ static bool HandlerRootExistsOnDataType(string parentExpression, string sourceParameterName, ITypeSymbol dataType)
+ {
+ var sourcePrefix = sourceParameterName + ".";
+ if (!parentExpression.StartsWith(sourcePrefix, StringComparison.Ordinal))
+ return false;
+
+ var remaining = parentExpression.Substring(sourcePrefix.Length);
+ var dotIndex = remaining.IndexOf('.');
+ var rootProperty = dotIndex >= 0 ? remaining.Substring(0, dotIndex) : remaining;
+
+ return HasProperty(dataType, rootProperty);
+ }
+
/// <summary>
/// Checks if the expression is a simple property chain (e.g., "Name" or "User.DisplayName").
/// Returns false for expressions with operators, method calls, or other complex constructs.
diff --git a/src/Controls/src/SourceGen/Visitors/ExpandMarkupsVisitor.cs b/src/Controls/src/SourceGen/Visitors/ExpandMarkupsVisitor.cs
index 81f25ef7fb..1b98a5f1a1 100644
--- a/src/Controls/src/SourceGen/Visitors/ExpandMarkupsVisitor.cs
+++ b/src/Controls/src/SourceGen/Visitors/ExpandMarkupsVisitor.cs
@@ -74,6 +74,11 @@ class ExpandMarkupsVisitor(SourceGenContext context) : IXamlNodeVisitor
// Extract expression code - single quotes are always transformed to double quotes
var expressionCode = CSharpExpressionHelpers.GetExpressionCode(trimmed);
+ // Resolve xmlns prefixes (e.g., local:Helper → fully qualified) before ABP syntax (e.g., target.(Grid.Row) → Grid.GetRow(target)).
+ expressionCode = CSharpExpressionHelpers.ResolveXmlnsPrefixes(expressionCode, node.NamespaceResolver, Context);
+ if (ReportStandaloneAttachedProperty(node, expressionCode))
+ return;
+ expressionCode = CSharpExpressionHelpers.TransformAttachedProperties(expressionCode, Context.Compilation);
node.Value = new Expression(expressionCode);
}
}
@@ -140,6 +145,11 @@ class ExpandMarkupsVisitor(SourceGenContext context) : IXamlNodeVisitor
{
// Extract expression code - single quotes are always transformed to double quotes
var expressionCode = CSharpExpressionHelpers.GetExpressionCode(markupString);
+ // Resolve xmlns prefixes before ABP syntax so prefixed ABPs become fully qualified type names.
+ expressionCode = CSharpExpressionHelpers.ResolveXmlnsPrefixes(expressionCode, markupnode.NamespaceResolver, Context);
+ if (ReportStandaloneAttachedProperty(markupnode, expressionCode))
+ return;
+ expressionCode = CSharpExpressionHelpers.TransformAttachedProperties(expressionCode, Context.Compilation);
node = new ValueNode(new Expression(expressionCode), markupnode.NamespaceResolver, markupnode.LineNumber, markupnode.LinePosition);
}
}
@@ -204,6 +214,19 @@ class ExpandMarkupsVisitor(SourceGenContext context) : IXamlNodeVisitor
}
}
+ bool ReportStandaloneAttachedProperty(IXmlLineInfo lineInfo, string expressionCode)
+ {
+ if (!CSharpExpressionHelpers.TryGetStandaloneAttachedProperty(expressionCode, Context.Compilation, out var attachedProperty))
+ return false;
+
+ var location = LocationHelpers.LocationCreate(Context.ProjectItem.RelativePath!, lineInfo, attachedProperty);
+ Context.ReportDiagnostic(Diagnostic.Create(
+ Descriptors.MemberResolution,
+ location,
+ $"Standalone attached property expression '{attachedProperty}' is not supported. Use a target such as 'this.{attachedProperty}' or 'element.{attachedProperty}'."));
+ return true;
+ }
+
bool TryResolveMarkupExtensionType(string name, IXmlNamespaceResolver nsResolver)
{
// Try to resolve FooExtension first, then Foo
diff --git a/src/Controls/tests/SourceGen.UnitTests/CSharpExpressionDiagnosticsTests.cs b/src/Controls/tests/SourceGen.UnitTests/CSharpExpressionDiagnosticsTests.cs
index b024efa235..b78361efc9 100644
--- a/src/Controls/tests/SourceGen.UnitTests/CSharpExpressionDiagnosticsTests.cs
+++ b/src/Controls/tests/SourceGen.UnitTests/CSharpExpressionDiagnosticsTests.cs
@@ -702,7 +702,7 @@ public partial class StringMethodPage : ContentPage
// Should compile without errors
Assert.DoesNotContain(result.Diagnostics, d => d.Severity == DiagnosticSeverity.Error);
-
+
// Generated code should have "x" (string literal), not 'x' (char literal)
Assert.Contains("\"x\"", output, StringComparison.Ordinal);
}
@@ -748,7 +748,7 @@ public partial class CharMethodPage : ContentPage
// Should have no source generator diagnostics (errors)
Assert.DoesNotContain(result.Diagnostics, d => d.Severity == DiagnosticSeverity.Error);
-
+
// Generated code should have 'x' (char literal)
Assert.Contains("'x'", output, StringComparison.Ordinal);
}
@@ -797,10 +797,10 @@ public partial class OperatorAliasPage : ContentPage
""";
var (result, output) = RunGenerator(xaml, codeBehind, assertNoCompilationErrors: false);
-
+
// Should have no source generator diagnostics (errors)
Assert.DoesNotContain(result.Diagnostics, d => d.Severity == DiagnosticSeverity.Error);
-
+
// Generated code should have C# operators instead of aliases
Assert.Contains("&&", output, StringComparison.Ordinal);
Assert.Contains("||", output, StringComparison.Ordinal);
@@ -809,4 +809,330 @@ public partial class OperatorAliasPage : ContentPage
Assert.Contains(" <= ", output, StringComparison.Ordinal);
Assert.Contains(" >= ", output, StringComparison.Ordinal);
}
+
+ [Fact]
+ public void XmlnsPrefix_TypeReference_UsesFullyQualifiedDisplayString()
+ {
+ var xaml =
+"""
+<?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:helpers="clr-namespace:TestApp.Helpers"
+ x:Class="TestApp.XmlnsPrefixPage">
+ <Label Text="{helpers:ExpressionHelper.Value}" />
+</ContentPage>
+""";
+
+ var codeBehind =
+"""
+using Microsoft.Maui.Controls;
+using Microsoft.Maui.Controls.Xaml;
+
+namespace TestApp.Helpers
+{
+ public static class ExpressionHelper
+ {
+ public static string Value => "Resolved";
+ }
+}
+
+namespace TestApp
+{
+ [XamlProcessing(XamlInflator.SourceGen)]
+ public partial class XmlnsPrefixPage : ContentPage
+ {
+ public XmlnsPrefixPage() => InitializeComponent();
+ }
+}
+""";
+
+ var (result, output) = RunGenerator(xaml, codeBehind);
+
+ Assert.DoesNotContain(result.Diagnostics, d => d.Severity == DiagnosticSeverity.Error);
+ Assert.Contains("global::TestApp.Helpers.ExpressionHelper.Value", output, StringComparison.Ordinal);
+ Assert.DoesNotContain("global::.", output, StringComparison.Ordinal);
+ Assert.DoesNotContain("<global namespace>", output, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void AttachedBindableProperty_WithNamedTarget_RewritesToGetter()
+ {
+ var xaml =
+"""
+<?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"
+ x:Class="TestApp.NamedAttachedPropertyPage">
+ <VerticalStackLayout>
+ <Button x:Name="MyButton" />
+ <Label Text="{MyButton.(Grid.Row)}" />
+ </VerticalStackLayout>
+</ContentPage>
+""";
+
+ var codeBehind =
+"""
+global using Microsoft.Maui.Controls;
+using Microsoft.Maui.Controls.Xaml;
+
+namespace TestApp;
+
+[XamlProcessing(XamlInflator.SourceGen)]
+public partial class NamedAttachedPropertyPage : ContentPage
+{
+ public NamedAttachedPropertyPage() => InitializeComponent();
+}
+""";
+
+ var (result, output) = RunGenerator(xaml, codeBehind);
+
+ Assert.DoesNotContain(result.Diagnostics, d => d.Severity == DiagnosticSeverity.Error);
+ Assert.Contains("Grid.GetRow(MyButton)", output, StringComparison.Ordinal);
+ Assert.DoesNotContain("__source", output, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void AttachedBindableProperty_WithXmlnsPrefix_RewritesToFullyQualifiedGetter()
+ {
+ var xaml =
+"""
+<?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:ios="clr-namespace:Microsoft.Maui.Controls.PlatformConfiguration.iOSSpecific;assembly=Microsoft.Maui.Controls"
+ x:Class="TestApp.PrefixedAttachedPropertyPage">
+ <Label IsVisible="{this.(ios:Page.UseSafeArea)}" />
+</ContentPage>
+""";
+
+ var codeBehind =
+"""
+using Microsoft.Maui.Controls;
+using Microsoft.Maui.Controls.Xaml;
+
+namespace TestApp;
+
+[XamlProcessing(XamlInflator.SourceGen)]
+public partial class PrefixedAttachedPropertyPage : ContentPage
+{
+ public PrefixedAttachedPropertyPage() => InitializeComponent();
+}
+""";
+
+ var (result, output) = RunGenerator(xaml, codeBehind);
+
+ Assert.DoesNotContain(result.Diagnostics, d => d.Severity == DiagnosticSeverity.Error);
+ Assert.Contains("Microsoft.Maui.Controls.PlatformConfiguration.iOSSpecific.Page.GetUseSafeArea(this)", output, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void AttachedBindableProperty_RewritesSkipStringAndInterpolatedLiteralSegments()
+ {
+ var xaml =
+"""
+<?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:helpers="clr-namespace:TestApp.Helpers"
+ x:Class="TestApp.LiteralAttachedPropertyPage">
+ <VerticalStackLayout>
+ <Label Text="{= 'helpers:ExpressionHelper (Grid.Row)'}" />
+ <Label Text="{$'helpers:ExpressionHelper (Grid.Row) {this.(Grid.Row)}'}" />
+ </VerticalStackLayout>
+</ContentPage>
+""";
+
+ var codeBehind =
+"""
+global using Microsoft.Maui.Controls;
+using Microsoft.Maui.Controls.Xaml;
+
+namespace TestApp.Helpers
+{
+ public static class ExpressionHelper
+ {
+ public static string Value => "Resolved";
+ }
+}
+
+namespace TestApp
+{
+ [XamlProcessing(XamlInflator.SourceGen)]
+ public partial class LiteralAttachedPropertyPage : ContentPage
+ {
+ public LiteralAttachedPropertyPage() => InitializeComponent();
+ }
+}
+""";
+
+ var (result, output) = RunGenerator(xaml, codeBehind);
+
+ Assert.DoesNotContain(result.Diagnostics, d => d.Severity == DiagnosticSeverity.Error);
+ Assert.Contains("\"helpers:ExpressionHelper (Grid.Row)\"", output, StringComparison.Ordinal);
+ Assert.Contains("GetRow(this)", output, StringComparison.Ordinal);
+ Assert.DoesNotContain("ExpressionHelper.Get", output, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void AttachedBindableProperty_StandaloneTarget_IsRejectedWithoutSourceRewrite()
+ {
+ var xaml =
+"""
+<?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"
+ x:Class="TestApp.StandaloneAttachedPropertyPage">
+ <Label Text="{(Grid.Row)}" />
+</ContentPage>
+""";
+
+ var codeBehind =
+"""
+global using Microsoft.Maui.Controls;
+using Microsoft.Maui.Controls.Xaml;
+
+namespace TestApp;
+
+[XamlProcessing(XamlInflator.SourceGen)]
+public partial class StandaloneAttachedPropertyPage : ContentPage
+{
+ public StandaloneAttachedPropertyPage() => InitializeComponent();
+}
+""";
+
+ var (result, output) = RunGenerator(xaml, codeBehind, assertNoCompilationErrors: false);
+
+ Assert.Contains(result.Diagnostics, d =>
+ d.Id == "MAUIX2002"
+ && d.GetMessage().Contains("Standalone attached property expression", StringComparison.Ordinal));
+ if (output is not null)
+ Assert.DoesNotContain("__source", output, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void ParenthesizedStaticMemberExpression_IsNotRejectedAsAttachedProperty()
+ {
+ var xaml =
+"""
+<?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"
+ x:Class="TestApp.ParenthesizedStaticMemberPage">
+ <Label Text="{(Math.PI).ToString()}" />
+</ContentPage>
+""";
+
+ var codeBehind =
+"""
+global using System;
+using Microsoft.Maui.Controls;
+using Microsoft.Maui.Controls.Xaml;
+
+namespace TestApp;
+
+[XamlProcessing(XamlInflator.SourceGen)]
+public partial class ParenthesizedStaticMemberPage : ContentPage
+{
+ public ParenthesizedStaticMemberPage() => InitializeComponent();
+}
+""";
+
+ var (result, output) = RunGenerator(xaml, codeBehind);
+
+ Assert.DoesNotContain(result.Diagnostics, d => d.Severity == DiagnosticSeverity.Error);
+ Assert.Contains("(Math.PI).ToString()", output, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void XmlnsPrefix_DoesNotRewriteNamedArgument()
+ {
+ var xaml =
+"""
+<?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:helpers="clr-namespace:TestApp.Helpers"
+ x:Class="TestApp.NamedArgumentPage">
+ <Label Text="{Format(helpers:ExpressionHelper)}" />
+</ContentPage>
+""";
+
+ var codeBehind =
+"""
+using Microsoft.Maui.Controls;
+using Microsoft.Maui.Controls.Xaml;
+
+namespace TestApp.Helpers
+{
+ public static class ExpressionHelper
+ {
+ public static string Value => "Type";
+ }
+}
+
+namespace TestApp
+{
+ [XamlProcessing(XamlInflator.SourceGen)]
+ public partial class NamedArgumentPage : ContentPage
+ {
+ public string ExpressionHelper => "Argument";
+ public string Format(string helpers) => helpers;
+ public NamedArgumentPage() => InitializeComponent();
+ }
+}
+""";
+
+ var (result, output) = RunGenerator(xaml, codeBehind, assertNoCompilationErrors: false);
+
+ Assert.Contains("Format(helpers:ExpressionHelper)", output, StringComparison.Ordinal);
+ Assert.DoesNotContain("Format(global::TestApp.Helpers.ExpressionHelper", output, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void AttachedBindableProperty_InTypedBindingExpression_DoesNotCreateStaticTypeHandler()
+ {
+ var xaml =
+"""
+<?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:TestApp"
+ x:Class="TestApp.TypedAttachedPropertyPage"
+ x:DataType="local:TypedAttachedPropertyViewModel">
+ <VerticalStackLayout>
+ <Button x:Name="button" Grid.Row="2" />
+ <Label Text="{Price + button.(Grid.Row)}" />
+ </VerticalStackLayout>
+</ContentPage>
+""";
+
+ var codeBehind =
+"""
+using System.ComponentModel;
+using Microsoft.Maui.Controls;
+using Microsoft.Maui.Controls.Xaml;
+
+namespace TestApp;
+
+public class TypedAttachedPropertyViewModel : INotifyPropertyChanged
+{
+ public int Price { get; set; } = 10;
+ public event PropertyChangedEventHandler? PropertyChanged;
+}
+
+[XamlProcessing(XamlInflator.SourceGen)]
+public partial class TypedAttachedPropertyPage : ContentPage
+{
+ public TypedAttachedPropertyPage() => InitializeComponent();
+}
+""";
+
+ var (result, output) = RunGenerator(xaml, codeBehind);
+
+ Assert.DoesNotContain(result.Diagnostics, d => d.Severity == DiagnosticSeverity.Error);
+ Assert.Contains("__source.Price", output, StringComparison.Ordinal);
+ Assert.Contains("GetRow(button)", output, StringComparison.Ordinal);
+ Assert.DoesNotContain("__source.Grid", output, StringComparison.Ordinal);
+ }
}
Resolve merge conflicts in the C# expressions source generator: - CSharpExpressionHelpers.cs: keep both the xmlns-prefix/attached-property helpers (this PR) and the interpolated-string identifier extraction + lambda method-group detection helpers (from inflight/current). - CSharpExpressionDiagnosticsTests.cs and CSharpExpressions.sgen.xaml.cs: keep the appended test methods from both branches. Also resolve a pre-existing MAUIX2017 diagnostic-ID collision on inflight/current (#35093 LambdaMethodGroupReference vs #35006 StructIntermediateNotSettable). LambdaMethodGroupReference keeps MAUIX2017; StructIntermediateNotSettable is renumbered to MAUIX2018 (descriptor, analyzer release notes, and its test updated accordingly). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2c02c03e-d835-437a-bb14-f9f2d0e108f3
…ions (#35007) <!-- Please let the below note in for people that find this PR --> > [!NOTE] > Are you waiting for the changes in this PR to be merged? > It would be very helpful if you could [test the resulting artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! ## Description Adds two new capabilities to the XAML C# expression source generator: ### 1. xmlns prefix type references in expressions Expressions can now reference types via XAML xmlns prefixes. The prefix is resolved to the fully qualified CLR type name before compilation. ```xml <ContentPage xmlns:local="clr-namespace:MyApp.Helpers"> <Label Text="{local:Helper.GetValue()}" /> </ContentPage> ``` Previously, `{local:Helper.GetValue()}` was incorrectly classified as a markup extension because the `prefix:Name` pattern was always treated as markup. Now, `prefix:Name.` (followed by `.`) is recognized as a type reference in an expression. ### 2. Attached Bindable Property (ABP) syntax Expressions support `(Type.Property)` syntax for reading attached properties, following the [x:Bind convention](https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension#attached-properties). ```xml <Grid> <Button x:Name="myBtn" Grid.Row="2" /> <Label Text="{$'Row {myBtn.(Grid.Row)}'}" /> </Grid> ``` The source generator transforms `target.(Type.Property)` into `Type.GetProperty(target)` calls. ### 3. Spec update Updated `docs/specs/XamlCSharpExpressions.md` with: - New **Attached Bindable Properties** section with syntax, examples, disambiguation rules, and diagnostics - New **Type References** section explaining xmlns prefix usage in expressions ## Changes | File | Change | |------|--------| | `CSharpExpressionHelpers.cs` | `StartsWithMarkupExtension` fix for `prefix:Type.` + `ResolveXmlnsPrefixes()` + `TransformAttachedProperties()` | | `ExpandMarkupsVisitor.cs` | Wire preprocessing into both ValueNode and MarkupNode expression paths | | `XamlCSharpExpressions.md` | Spec: ABP section, Type References section | | `CSharpExpressions.sgen.xaml[.cs]` | Tests for xmlns prefix and ABP access | --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2c02c03e-d835-437a-bb14-f9f2d0e108f3
…ions (#35007) <!-- Please let the below note in for people that find this PR --> > [!NOTE] > Are you waiting for the changes in this PR to be merged? > It would be very helpful if you could [test the resulting artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! ## Description Adds two new capabilities to the XAML C# expression source generator: ### 1. xmlns prefix type references in expressions Expressions can now reference types via XAML xmlns prefixes. The prefix is resolved to the fully qualified CLR type name before compilation. ```xml <ContentPage xmlns:local="clr-namespace:MyApp.Helpers"> <Label Text="{local:Helper.GetValue()}" /> </ContentPage> ``` Previously, `{local:Helper.GetValue()}` was incorrectly classified as a markup extension because the `prefix:Name` pattern was always treated as markup. Now, `prefix:Name.` (followed by `.`) is recognized as a type reference in an expression. ### 2. Attached Bindable Property (ABP) syntax Expressions support `(Type.Property)` syntax for reading attached properties, following the [x:Bind convention](https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension#attached-properties). ```xml <Grid> <Button x:Name="myBtn" Grid.Row="2" /> <Label Text="{$'Row {myBtn.(Grid.Row)}'}" /> </Grid> ``` The source generator transforms `target.(Type.Property)` into `Type.GetProperty(target)` calls. ### 3. Spec update Updated `docs/specs/XamlCSharpExpressions.md` with: - New **Attached Bindable Properties** section with syntax, examples, disambiguation rules, and diagnostics - New **Type References** section explaining xmlns prefix usage in expressions ## Changes | File | Change | |------|--------| | `CSharpExpressionHelpers.cs` | `StartsWithMarkupExtension` fix for `prefix:Type.` + `ResolveXmlnsPrefixes()` + `TransformAttachedProperties()` | | `ExpandMarkupsVisitor.cs` | Wire preprocessing into both ValueNode and MarkupNode expression paths | | `XamlCSharpExpressions.md` | Spec: ABP section, Type References section | | `CSharpExpressions.sgen.xaml[.cs]` | Tests for xmlns prefix and ABP access | --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2c02c03e-d835-437a-bb14-f9f2d0e108f3
…ions (#35007) <!-- Please let the below note in for people that find this PR --> > [!NOTE] > Are you waiting for the changes in this PR to be merged? > It would be very helpful if you could [test the resulting artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! ## Description Adds two new capabilities to the XAML C# expression source generator: ### 1. xmlns prefix type references in expressions Expressions can now reference types via XAML xmlns prefixes. The prefix is resolved to the fully qualified CLR type name before compilation. ```xml <ContentPage xmlns:local="clr-namespace:MyApp.Helpers"> <Label Text="{local:Helper.GetValue()}" /> </ContentPage> ``` Previously, `{local:Helper.GetValue()}` was incorrectly classified as a markup extension because the `prefix:Name` pattern was always treated as markup. Now, `prefix:Name.` (followed by `.`) is recognized as a type reference in an expression. ### 2. Attached Bindable Property (ABP) syntax Expressions support `(Type.Property)` syntax for reading attached properties, following the [x:Bind convention](https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension#attached-properties). ```xml <Grid> <Button x:Name="myBtn" Grid.Row="2" /> <Label Text="{$'Row {myBtn.(Grid.Row)}'}" /> </Grid> ``` The source generator transforms `target.(Type.Property)` into `Type.GetProperty(target)` calls. ### 3. Spec update Updated `docs/specs/XamlCSharpExpressions.md` with: - New **Attached Bindable Properties** section with syntax, examples, disambiguation rules, and diagnostics - New **Type References** section explaining xmlns prefix usage in expressions ## Changes | File | Change | |------|--------| | `CSharpExpressionHelpers.cs` | `StartsWithMarkupExtension` fix for `prefix:Type.` + `ResolveXmlnsPrefixes()` + `TransformAttachedProperties()` | | `ExpandMarkupsVisitor.cs` | Wire preprocessing into both ValueNode and MarkupNode expression paths | | `XamlCSharpExpressions.md` | Spec: ABP section, Type References section | | `CSharpExpressions.sgen.xaml[.cs]` | Tests for xmlns prefix and ABP access | --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2c02c03e-d835-437a-bb14-f9f2d0e108f3
…ions (#35007) <!-- Please let the below note in for people that find this PR --> > [!NOTE] > Are you waiting for the changes in this PR to be merged? > It would be very helpful if you could [test the resulting artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! ## Description Adds two new capabilities to the XAML C# expression source generator: ### 1. xmlns prefix type references in expressions Expressions can now reference types via XAML xmlns prefixes. The prefix is resolved to the fully qualified CLR type name before compilation. ```xml <ContentPage xmlns:local="clr-namespace:MyApp.Helpers"> <Label Text="{local:Helper.GetValue()}" /> </ContentPage> ``` Previously, `{local:Helper.GetValue()}` was incorrectly classified as a markup extension because the `prefix:Name` pattern was always treated as markup. Now, `prefix:Name.` (followed by `.`) is recognized as a type reference in an expression. ### 2. Attached Bindable Property (ABP) syntax Expressions support `(Type.Property)` syntax for reading attached properties, following the [x:Bind convention](https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension#attached-properties). ```xml <Grid> <Button x:Name="myBtn" Grid.Row="2" /> <Label Text="{$'Row {myBtn.(Grid.Row)}'}" /> </Grid> ``` The source generator transforms `target.(Type.Property)` into `Type.GetProperty(target)` calls. ### 3. Spec update Updated `docs/specs/XamlCSharpExpressions.md` with: - New **Attached Bindable Properties** section with syntax, examples, disambiguation rules, and diagnostics - New **Type References** section explaining xmlns prefix usage in expressions ## Changes | File | Change | |------|--------| | `CSharpExpressionHelpers.cs` | `StartsWithMarkupExtension` fix for `prefix:Type.` + `ResolveXmlnsPrefixes()` + `TransformAttachedProperties()` | | `ExpandMarkupsVisitor.cs` | Wire preprocessing into both ValueNode and MarkupNode expression paths | | `XamlCSharpExpressions.md` | Spec: ABP section, Type References section | | `CSharpExpressions.sgen.xaml[.cs]` | Tests for xmlns prefix and ABP access | --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2c02c03e-d835-437a-bb14-f9f2d0e108f3
…ions (#35007) <!-- Please let the below note in for people that find this PR --> > [!NOTE] > Are you waiting for the changes in this PR to be merged? > It would be very helpful if you could [test the resulting artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! ## Description Adds two new capabilities to the XAML C# expression source generator: ### 1. xmlns prefix type references in expressions Expressions can now reference types via XAML xmlns prefixes. The prefix is resolved to the fully qualified CLR type name before compilation. ```xml <ContentPage xmlns:local="clr-namespace:MyApp.Helpers"> <Label Text="{local:Helper.GetValue()}" /> </ContentPage> ``` Previously, `{local:Helper.GetValue()}` was incorrectly classified as a markup extension because the `prefix:Name` pattern was always treated as markup. Now, `prefix:Name.` (followed by `.`) is recognized as a type reference in an expression. ### 2. Attached Bindable Property (ABP) syntax Expressions support `(Type.Property)` syntax for reading attached properties, following the [x:Bind convention](https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension#attached-properties). ```xml <Grid> <Button x:Name="myBtn" Grid.Row="2" /> <Label Text="{$'Row {myBtn.(Grid.Row)}'}" /> </Grid> ``` The source generator transforms `target.(Type.Property)` into `Type.GetProperty(target)` calls. ### 3. Spec update Updated `docs/specs/XamlCSharpExpressions.md` with: - New **Attached Bindable Properties** section with syntax, examples, disambiguation rules, and diagnostics - New **Type References** section explaining xmlns prefix usage in expressions ## Changes | File | Change | |------|--------| | `CSharpExpressionHelpers.cs` | `StartsWithMarkupExtension` fix for `prefix:Type.` + `ResolveXmlnsPrefixes()` + `TransformAttachedProperties()` | | `ExpandMarkupsVisitor.cs` | Wire preprocessing into both ValueNode and MarkupNode expression paths | | `XamlCSharpExpressions.md` | Spec: ABP section, Type References section | | `CSharpExpressions.sgen.xaml[.cs]` | Tests for xmlns prefix and ABP access | --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2c02c03e-d835-437a-bb14-f9f2d0e108f3
…ions (#35007) <!-- Please let the below note in for people that find this PR --> > [!NOTE] > Are you waiting for the changes in this PR to be merged? > It would be very helpful if you could [test the resulting artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! ## Description Adds two new capabilities to the XAML C# expression source generator: ### 1. xmlns prefix type references in expressions Expressions can now reference types via XAML xmlns prefixes. The prefix is resolved to the fully qualified CLR type name before compilation. ```xml <ContentPage xmlns:local="clr-namespace:MyApp.Helpers"> <Label Text="{local:Helper.GetValue()}" /> </ContentPage> ``` Previously, `{local:Helper.GetValue()}` was incorrectly classified as a markup extension because the `prefix:Name` pattern was always treated as markup. Now, `prefix:Name.` (followed by `.`) is recognized as a type reference in an expression. ### 2. Attached Bindable Property (ABP) syntax Expressions support `(Type.Property)` syntax for reading attached properties, following the [x:Bind convention](https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension#attached-properties). ```xml <Grid> <Button x:Name="myBtn" Grid.Row="2" /> <Label Text="{$'Row {myBtn.(Grid.Row)}'}" /> </Grid> ``` The source generator transforms `target.(Type.Property)` into `Type.GetProperty(target)` calls. ### 3. Spec update Updated `docs/specs/XamlCSharpExpressions.md` with: - New **Attached Bindable Properties** section with syntax, examples, disambiguation rules, and diagnostics - New **Type References** section explaining xmlns prefix usage in expressions ## Changes | File | Change | |------|--------| | `CSharpExpressionHelpers.cs` | `StartsWithMarkupExtension` fix for `prefix:Type.` + `ResolveXmlnsPrefixes()` + `TransformAttachedProperties()` | | `ExpandMarkupsVisitor.cs` | Wire preprocessing into both ValueNode and MarkupNode expression paths | | `XamlCSharpExpressions.md` | Spec: ABP section, Type References section | | `CSharpExpressions.sgen.xaml[.cs]` | Tests for xmlns prefix and ABP access | --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2c02c03e-d835-437a-bb14-f9f2d0e108f3
…ions (#35007) <!-- Please let the below note in for people that find this PR --> > [!NOTE] > Are you waiting for the changes in this PR to be merged? > It would be very helpful if you could [test the resulting artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! ## Description Adds two new capabilities to the XAML C# expression source generator: ### 1. xmlns prefix type references in expressions Expressions can now reference types via XAML xmlns prefixes. The prefix is resolved to the fully qualified CLR type name before compilation. ```xml <ContentPage xmlns:local="clr-namespace:MyApp.Helpers"> <Label Text="{local:Helper.GetValue()}" /> </ContentPage> ``` Previously, `{local:Helper.GetValue()}` was incorrectly classified as a markup extension because the `prefix:Name` pattern was always treated as markup. Now, `prefix:Name.` (followed by `.`) is recognized as a type reference in an expression. ### 2. Attached Bindable Property (ABP) syntax Expressions support `(Type.Property)` syntax for reading attached properties, following the [x:Bind convention](https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension#attached-properties). ```xml <Grid> <Button x:Name="myBtn" Grid.Row="2" /> <Label Text="{$'Row {myBtn.(Grid.Row)}'}" /> </Grid> ``` The source generator transforms `target.(Type.Property)` into `Type.GetProperty(target)` calls. ### 3. Spec update Updated `docs/specs/XamlCSharpExpressions.md` with: - New **Attached Bindable Properties** section with syntax, examples, disambiguation rules, and diagnostics - New **Type References** section explaining xmlns prefix usage in expressions ## Changes | File | Change | |------|--------| | `CSharpExpressionHelpers.cs` | `StartsWithMarkupExtension` fix for `prefix:Type.` + `ResolveXmlnsPrefixes()` + `TransformAttachedProperties()` | | `ExpandMarkupsVisitor.cs` | Wire preprocessing into both ValueNode and MarkupNode expression paths | | `XamlCSharpExpressions.md` | Spec: ABP section, Type References section | | `CSharpExpressions.sgen.xaml[.cs]` | Tests for xmlns prefix and ABP access | --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2c02c03e-d835-437a-bb14-f9f2d0e108f3
…ions (#35007) <!-- Please let the below note in for people that find this PR --> > [!NOTE] > Are you waiting for the changes in this PR to be merged? > It would be very helpful if you could [test the resulting artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! ## Description Adds two new capabilities to the XAML C# expression source generator: ### 1. xmlns prefix type references in expressions Expressions can now reference types via XAML xmlns prefixes. The prefix is resolved to the fully qualified CLR type name before compilation. ```xml <ContentPage xmlns:local="clr-namespace:MyApp.Helpers"> <Label Text="{local:Helper.GetValue()}" /> </ContentPage> ``` Previously, `{local:Helper.GetValue()}` was incorrectly classified as a markup extension because the `prefix:Name` pattern was always treated as markup. Now, `prefix:Name.` (followed by `.`) is recognized as a type reference in an expression. ### 2. Attached Bindable Property (ABP) syntax Expressions support `(Type.Property)` syntax for reading attached properties, following the [x:Bind convention](https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension#attached-properties). ```xml <Grid> <Button x:Name="myBtn" Grid.Row="2" /> <Label Text="{$'Row {myBtn.(Grid.Row)}'}" /> </Grid> ``` The source generator transforms `target.(Type.Property)` into `Type.GetProperty(target)` calls. ### 3. Spec update Updated `docs/specs/XamlCSharpExpressions.md` with: - New **Attached Bindable Properties** section with syntax, examples, disambiguation rules, and diagnostics - New **Type References** section explaining xmlns prefix usage in expressions ## Changes | File | Change | |------|--------| | `CSharpExpressionHelpers.cs` | `StartsWithMarkupExtension` fix for `prefix:Type.` + `ResolveXmlnsPrefixes()` + `TransformAttachedProperties()` | | `ExpandMarkupsVisitor.cs` | Wire preprocessing into both ValueNode and MarkupNode expression paths | | `XamlCSharpExpressions.md` | Spec: ABP section, Type References section | | `CSharpExpressions.sgen.xaml[.cs]` | Tests for xmlns prefix and ABP access | --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2c02c03e-d835-437a-bb14-f9f2d0e108f3
…ions (#35007) <!-- Please let the below note in for people that find this PR --> > [!NOTE] > Are you waiting for the changes in this PR to be merged? > It would be very helpful if you could [test the resulting artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! ## Description Adds two new capabilities to the XAML C# expression source generator: ### 1. xmlns prefix type references in expressions Expressions can now reference types via XAML xmlns prefixes. The prefix is resolved to the fully qualified CLR type name before compilation. ```xml <ContentPage xmlns:local="clr-namespace:MyApp.Helpers"> <Label Text="{local:Helper.GetValue()}" /> </ContentPage> ``` Previously, `{local:Helper.GetValue()}` was incorrectly classified as a markup extension because the `prefix:Name` pattern was always treated as markup. Now, `prefix:Name.` (followed by `.`) is recognized as a type reference in an expression. ### 2. Attached Bindable Property (ABP) syntax Expressions support `(Type.Property)` syntax for reading attached properties, following the [x:Bind convention](https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension#attached-properties). ```xml <Grid> <Button x:Name="myBtn" Grid.Row="2" /> <Label Text="{$'Row {myBtn.(Grid.Row)}'}" /> </Grid> ``` The source generator transforms `target.(Type.Property)` into `Type.GetProperty(target)` calls. ### 3. Spec update Updated `docs/specs/XamlCSharpExpressions.md` with: - New **Attached Bindable Properties** section with syntax, examples, disambiguation rules, and diagnostics - New **Type References** section explaining xmlns prefix usage in expressions ## Changes | File | Change | |------|--------| | `CSharpExpressionHelpers.cs` | `StartsWithMarkupExtension` fix for `prefix:Type.` + `ResolveXmlnsPrefixes()` + `TransformAttachedProperties()` | | `ExpandMarkupsVisitor.cs` | Wire preprocessing into both ValueNode and MarkupNode expression paths | | `XamlCSharpExpressions.md` | Spec: ABP section, Type References section | | `CSharpExpressions.sgen.xaml[.cs]` | Tests for xmlns prefix and ABP access | --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2c02c03e-d835-437a-bb14-f9f2d0e108f3
…ions (#35007) <!-- Please let the below note in for people that find this PR --> > [!NOTE] > Are you waiting for the changes in this PR to be merged? > It would be very helpful if you could [test the resulting artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! ## Description Adds two new capabilities to the XAML C# expression source generator: ### 1. xmlns prefix type references in expressions Expressions can now reference types via XAML xmlns prefixes. The prefix is resolved to the fully qualified CLR type name before compilation. ```xml <ContentPage xmlns:local="clr-namespace:MyApp.Helpers"> <Label Text="{local:Helper.GetValue()}" /> </ContentPage> ``` Previously, `{local:Helper.GetValue()}` was incorrectly classified as a markup extension because the `prefix:Name` pattern was always treated as markup. Now, `prefix:Name.` (followed by `.`) is recognized as a type reference in an expression. ### 2. Attached Bindable Property (ABP) syntax Expressions support `(Type.Property)` syntax for reading attached properties, following the [x:Bind convention](https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension#attached-properties). ```xml <Grid> <Button x:Name="myBtn" Grid.Row="2" /> <Label Text="{$'Row {myBtn.(Grid.Row)}'}" /> </Grid> ``` The source generator transforms `target.(Type.Property)` into `Type.GetProperty(target)` calls. ### 3. Spec update Updated `docs/specs/XamlCSharpExpressions.md` with: - New **Attached Bindable Properties** section with syntax, examples, disambiguation rules, and diagnostics - New **Type References** section explaining xmlns prefix usage in expressions ## Changes | File | Change | |------|--------| | `CSharpExpressionHelpers.cs` | `StartsWithMarkupExtension` fix for `prefix:Type.` + `ResolveXmlnsPrefixes()` + `TransformAttachedProperties()` | | `ExpandMarkupsVisitor.cs` | Wire preprocessing into both ValueNode and MarkupNode expression paths | | `XamlCSharpExpressions.md` | Spec: ABP section, Type References section | | `CSharpExpressions.sgen.xaml[.cs]` | Tests for xmlns prefix and ABP access | --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2c02c03e-d835-437a-bb14-f9f2d0e108f3
…ions (#35007) <!-- Please let the below note in for people that find this PR --> > [!NOTE] > Are you waiting for the changes in this PR to be merged? > It would be very helpful if you could [test the resulting artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! ## Description Adds two new capabilities to the XAML C# expression source generator: ### 1. xmlns prefix type references in expressions Expressions can now reference types via XAML xmlns prefixes. The prefix is resolved to the fully qualified CLR type name before compilation. ```xml <ContentPage xmlns:local="clr-namespace:MyApp.Helpers"> <Label Text="{local:Helper.GetValue()}" /> </ContentPage> ``` Previously, `{local:Helper.GetValue()}` was incorrectly classified as a markup extension because the `prefix:Name` pattern was always treated as markup. Now, `prefix:Name.` (followed by `.`) is recognized as a type reference in an expression. ### 2. Attached Bindable Property (ABP) syntax Expressions support `(Type.Property)` syntax for reading attached properties, following the [x:Bind convention](https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension#attached-properties). ```xml <Grid> <Button x:Name="myBtn" Grid.Row="2" /> <Label Text="{$'Row {myBtn.(Grid.Row)}'}" /> </Grid> ``` The source generator transforms `target.(Type.Property)` into `Type.GetProperty(target)` calls. ### 3. Spec update Updated `docs/specs/XamlCSharpExpressions.md` with: - New **Attached Bindable Properties** section with syntax, examples, disambiguation rules, and diagnostics - New **Type References** section explaining xmlns prefix usage in expressions ## Changes | File | Change | |------|--------| | `CSharpExpressionHelpers.cs` | `StartsWithMarkupExtension` fix for `prefix:Type.` + `ResolveXmlnsPrefixes()` + `TransformAttachedProperties()` | | `ExpandMarkupsVisitor.cs` | Wire preprocessing into both ValueNode and MarkupNode expression paths | | `XamlCSharpExpressions.md` | Spec: ABP section, Type References section | | `CSharpExpressions.sgen.xaml[.cs]` | Tests for xmlns prefix and ABP access | --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2c02c03e-d835-437a-bb14-f9f2d0e108f3
…ions (#35007) <!-- Please let the below note in for people that find this PR --> > [!NOTE] > Are you waiting for the changes in this PR to be merged? > It would be very helpful if you could [test the resulting artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! ## Description Adds two new capabilities to the XAML C# expression source generator: ### 1. xmlns prefix type references in expressions Expressions can now reference types via XAML xmlns prefixes. The prefix is resolved to the fully qualified CLR type name before compilation. ```xml <ContentPage xmlns:local="clr-namespace:MyApp.Helpers"> <Label Text="{local:Helper.GetValue()}" /> </ContentPage> ``` Previously, `{local:Helper.GetValue()}` was incorrectly classified as a markup extension because the `prefix:Name` pattern was always treated as markup. Now, `prefix:Name.` (followed by `.`) is recognized as a type reference in an expression. ### 2. Attached Bindable Property (ABP) syntax Expressions support `(Type.Property)` syntax for reading attached properties, following the [x:Bind convention](https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension#attached-properties). ```xml <Grid> <Button x:Name="myBtn" Grid.Row="2" /> <Label Text="{$'Row {myBtn.(Grid.Row)}'}" /> </Grid> ``` The source generator transforms `target.(Type.Property)` into `Type.GetProperty(target)` calls. ### 3. Spec update Updated `docs/specs/XamlCSharpExpressions.md` with: - New **Attached Bindable Properties** section with syntax, examples, disambiguation rules, and diagnostics - New **Type References** section explaining xmlns prefix usage in expressions ## Changes | File | Change | |------|--------| | `CSharpExpressionHelpers.cs` | `StartsWithMarkupExtension` fix for `prefix:Type.` + `ResolveXmlnsPrefixes()` + `TransformAttachedProperties()` | | `ExpandMarkupsVisitor.cs` | Wire preprocessing into both ValueNode and MarkupNode expression paths | | `XamlCSharpExpressions.md` | Spec: ABP section, Type References section | | `CSharpExpressions.sgen.xaml[.cs]` | Tests for xmlns prefix and ABP access | --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2c02c03e-d835-437a-bb14-f9f2d0e108f3
…ions (#35007) <!-- Please let the below note in for people that find this PR --> > [!NOTE] > Are you waiting for the changes in this PR to be merged? > It would be very helpful if you could [test the resulting artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! ## Description Adds two new capabilities to the XAML C# expression source generator: ### 1. xmlns prefix type references in expressions Expressions can now reference types via XAML xmlns prefixes. The prefix is resolved to the fully qualified CLR type name before compilation. ```xml <ContentPage xmlns:local="clr-namespace:MyApp.Helpers"> <Label Text="{local:Helper.GetValue()}" /> </ContentPage> ``` Previously, `{local:Helper.GetValue()}` was incorrectly classified as a markup extension because the `prefix:Name` pattern was always treated as markup. Now, `prefix:Name.` (followed by `.`) is recognized as a type reference in an expression. ### 2. Attached Bindable Property (ABP) syntax Expressions support `(Type.Property)` syntax for reading attached properties, following the [x:Bind convention](https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension#attached-properties). ```xml <Grid> <Button x:Name="myBtn" Grid.Row="2" /> <Label Text="{$'Row {myBtn.(Grid.Row)}'}" /> </Grid> ``` The source generator transforms `target.(Type.Property)` into `Type.GetProperty(target)` calls. ### 3. Spec update Updated `docs/specs/XamlCSharpExpressions.md` with: - New **Attached Bindable Properties** section with syntax, examples, disambiguation rules, and diagnostics - New **Type References** section explaining xmlns prefix usage in expressions ## Changes | File | Change | |------|--------| | `CSharpExpressionHelpers.cs` | `StartsWithMarkupExtension` fix for `prefix:Type.` + `ResolveXmlnsPrefixes()` + `TransformAttachedProperties()` | | `ExpandMarkupsVisitor.cs` | Wire preprocessing into both ValueNode and MarkupNode expression paths | | `XamlCSharpExpressions.md` | Spec: ABP section, Type References section | | `CSharpExpressions.sgen.xaml[.cs]` | Tests for xmlns prefix and ABP access | --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2c02c03e-d835-437a-bb14-f9f2d0e108f3
…ions (#35007) <!-- Please let the below note in for people that find this PR --> > [!NOTE] > Are you waiting for the changes in this PR to be merged? > It would be very helpful if you could [test the resulting artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! ## Description Adds two new capabilities to the XAML C# expression source generator: ### 1. xmlns prefix type references in expressions Expressions can now reference types via XAML xmlns prefixes. The prefix is resolved to the fully qualified CLR type name before compilation. ```xml <ContentPage xmlns:local="clr-namespace:MyApp.Helpers"> <Label Text="{local:Helper.GetValue()}" /> </ContentPage> ``` Previously, `{local:Helper.GetValue()}` was incorrectly classified as a markup extension because the `prefix:Name` pattern was always treated as markup. Now, `prefix:Name.` (followed by `.`) is recognized as a type reference in an expression. ### 2. Attached Bindable Property (ABP) syntax Expressions support `(Type.Property)` syntax for reading attached properties, following the [x:Bind convention](https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension#attached-properties). ```xml <Grid> <Button x:Name="myBtn" Grid.Row="2" /> <Label Text="{$'Row {myBtn.(Grid.Row)}'}" /> </Grid> ``` The source generator transforms `target.(Type.Property)` into `Type.GetProperty(target)` calls. ### 3. Spec update Updated `docs/specs/XamlCSharpExpressions.md` with: - New **Attached Bindable Properties** section with syntax, examples, disambiguation rules, and diagnostics - New **Type References** section explaining xmlns prefix usage in expressions ## Changes | File | Change | |------|--------| | `CSharpExpressionHelpers.cs` | `StartsWithMarkupExtension` fix for `prefix:Type.` + `ResolveXmlnsPrefixes()` + `TransformAttachedProperties()` | | `ExpandMarkupsVisitor.cs` | Wire preprocessing into both ValueNode and MarkupNode expression paths | | `XamlCSharpExpressions.md` | Spec: ABP section, Type References section | | `CSharpExpressions.sgen.xaml[.cs]` | Tests for xmlns prefix and ABP access | --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2c02c03e-d835-437a-bb14-f9f2d0e108f3
…ions (#35007) <!-- Please let the below note in for people that find this PR --> > [!NOTE] > Are you waiting for the changes in this PR to be merged? > It would be very helpful if you could [test the resulting artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! ## Description Adds two new capabilities to the XAML C# expression source generator: ### 1. xmlns prefix type references in expressions Expressions can now reference types via XAML xmlns prefixes. The prefix is resolved to the fully qualified CLR type name before compilation. ```xml <ContentPage xmlns:local="clr-namespace:MyApp.Helpers"> <Label Text="{local:Helper.GetValue()}" /> </ContentPage> ``` Previously, `{local:Helper.GetValue()}` was incorrectly classified as a markup extension because the `prefix:Name` pattern was always treated as markup. Now, `prefix:Name.` (followed by `.`) is recognized as a type reference in an expression. ### 2. Attached Bindable Property (ABP) syntax Expressions support `(Type.Property)` syntax for reading attached properties, following the [x:Bind convention](https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension#attached-properties). ```xml <Grid> <Button x:Name="myBtn" Grid.Row="2" /> <Label Text="{$'Row {myBtn.(Grid.Row)}'}" /> </Grid> ``` The source generator transforms `target.(Type.Property)` into `Type.GetProperty(target)` calls. ### 3. Spec update Updated `docs/specs/XamlCSharpExpressions.md` with: - New **Attached Bindable Properties** section with syntax, examples, disambiguation rules, and diagnostics - New **Type References** section explaining xmlns prefix usage in expressions ## Changes | File | Change | |------|--------| | `CSharpExpressionHelpers.cs` | `StartsWithMarkupExtension` fix for `prefix:Type.` + `ResolveXmlnsPrefixes()` + `TransformAttachedProperties()` | | `ExpandMarkupsVisitor.cs` | Wire preprocessing into both ValueNode and MarkupNode expression paths | | `XamlCSharpExpressions.md` | Spec: ABP section, Type References section | | `CSharpExpressions.sgen.xaml[.cs]` | Tests for xmlns prefix and ABP access | --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2c02c03e-d835-437a-bb14-f9f2d0e108f3
…ions (#35007) <!-- Please let the below note in for people that find this PR --> > [!NOTE] > Are you waiting for the changes in this PR to be merged? > It would be very helpful if you could [test the resulting artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! ## Description Adds two new capabilities to the XAML C# expression source generator: ### 1. xmlns prefix type references in expressions Expressions can now reference types via XAML xmlns prefixes. The prefix is resolved to the fully qualified CLR type name before compilation. ```xml <ContentPage xmlns:local="clr-namespace:MyApp.Helpers"> <Label Text="{local:Helper.GetValue()}" /> </ContentPage> ``` Previously, `{local:Helper.GetValue()}` was incorrectly classified as a markup extension because the `prefix:Name` pattern was always treated as markup. Now, `prefix:Name.` (followed by `.`) is recognized as a type reference in an expression. ### 2. Attached Bindable Property (ABP) syntax Expressions support `(Type.Property)` syntax for reading attached properties, following the [x:Bind convention](https://learn.microsoft.com/en-us/windows/apps/develop/platform/xaml/x-bind-markup-extension#attached-properties). ```xml <Grid> <Button x:Name="myBtn" Grid.Row="2" /> <Label Text="{$'Row {myBtn.(Grid.Row)}'}" /> </Grid> ``` The source generator transforms `target.(Type.Property)` into `Type.GetProperty(target)` calls. ### 3. Spec update Updated `docs/specs/XamlCSharpExpressions.md` with: - New **Attached Bindable Properties** section with syntax, examples, disambiguation rules, and diagnostics - New **Type References** section explaining xmlns prefix usage in expressions ## Changes | File | Change | |------|--------| | `CSharpExpressionHelpers.cs` | `StartsWithMarkupExtension` fix for `prefix:Type.` + `ResolveXmlnsPrefixes()` + `TransformAttachedProperties()` | | `ExpandMarkupsVisitor.cs` | Wire preprocessing into both ValueNode and MarkupNode expression paths | | `XamlCSharpExpressions.md` | Spec: ABP section, Type References section | | `CSharpExpressions.sgen.xaml[.cs]` | Tests for xmlns prefix and ABP access | --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2c02c03e-d835-437a-bb14-f9f2d0e108f3
Note
Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!
Description
Adds two new capabilities to the XAML C# expression source generator:
1. xmlns prefix type references in expressions
Expressions can now reference types via XAML xmlns prefixes. The prefix is resolved to the fully qualified CLR type name before compilation.
Previously,
{local:Helper.GetValue()}was incorrectly classified as a markup extension because theprefix:Namepattern was always treated as markup. Now,prefix:Name.(followed by.) is recognized as a type reference in an expression.2. Attached Bindable Property (ABP) syntax
Expressions support
(Type.Property)syntax for reading attached properties, following the x:Bind convention.The source generator transforms
target.(Type.Property)intoType.GetProperty(target)calls.3. Spec update
Updated
docs/specs/XamlCSharpExpressions.mdwith:Changes
CSharpExpressionHelpers.csStartsWithMarkupExtensionfix forprefix:Type.+ResolveXmlnsPrefixes()+TransformAttachedProperties()ExpandMarkupsVisitor.csXamlCSharpExpressions.mdCSharpExpressions.sgen.xaml[.cs]