Repository navigation
Fix XAML IntelliSense false positives, missing diagnostics, and completion gaps - #380
Chiara Mooney (chiaramooney) wants to merge 9 commits into
Conversation
…on gaps - #351: Binding ElementName inside a template resolves through outer namescopes. - #352: x:Bind string sources are accepted for any target (XamlBindingHelper conversion). - #357: Add diagnostics WXAML0036-0048 for missing x:Key, WPF-only markup, non-constructible elements, x:Name+Name, text content, double assignment, x:Load without name, empty handlers, TwoWay to read-only, missing ResourceDictionary Source, BasedOn cycles/incompatibility, StaticResource type mismatch, and x:Bind to a method without a call; unknown Style TargetType. - #358: Offer project types for type-valued attributes, static x:Bind roots (completion, hover, definition), x: primitives and plain CLR objects in resources, import fix for CLR classes; hide abstract types, Name beside x:Name, x:Type/x:Static; no elements inside values or after root. Fixes #351, #352, #357, #358 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
- Share one constructibility rule between completion and WXAML0038: allow enums, structs, and text-created framework types (FontFamily); require a parameterless constructor on project classes. - Skip design-time and mc:Ignorable markup in WXAML0037 and WXAML0041. - Binding ElementName completion and rename include enclosing namescopes. - Only exclude NuGet package sources from project type lists. - Rank imported project types last for TargetType/SourcePageType. - WXAML0037 suggests the WinUI replacement. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
- Diagnostics only report what the compiler rejects: primitive resource values, text in non-UIElement content, Name on non-FrameworkElements, design-time subtrees, and linked dictionaries no longer false-positive. - Constructibility follows the compiler rule: public parameterless ctor, or a framework text type such as FontFamily. - Rename checks resolve scope the same way as occurrence collection, so template references cannot be retargeted or skip the x:Bind guard. - Project-type completion shares one instantiable-type filter. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
WXAML0045 needed file-system access and filename heuristics for a warning that a build already catches; the BasedOn memo only helped implausibly long style chains. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…ed-property method binds - XAML language primitives (x:String) are constructible like structs and enums. - Rename refuses any change to which element a classic ElementName binding resolves to, in both directions, using one shared reference enumerator. - The x:Bind method-without-call check covers every non-event attribute, including attached properties, instead of plain properties only. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Same-name renames skip the ElementName resolution check. IsFoundFirst now compares namescope order including shadowed elements, so a declaration hidden by a nested reuse of its old name is still detected as a capture. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…-intellisense-bugs-ddc
VSIX Build
Updated 2026-11-24 19:47:42 UTC · commit |
There was a problem hiding this comment.
PR Review — chiaramooney-fix-xaml-intellisense-bugs-ddc vs origin/main (7 commits, 25 files, +1563/-106 lines)
Summary
Critical: 0 High: 0 Medium: 5 Low: 3
Coverage
security ✓ clean
correctness ⚠ 6 findings
extension-ux ⚠ 2 findings
alternative-solution ⚠ 2 findings
test-coverage ⚠ 2 findings
docs-and-samples ✓ clean
packaging ✓ clean
multi-model ✓ 0/0 critical+high confirmed (4 candidate highs downgraded to medium/low)
Findings
M1 server/src/WinUiXaml.LanguageServer/CompletionProvider.ElementsAndAttributes.cs:160-172 correctness IsResourceChildContext resolves preceding closed sibling when '<' follows '/>' without whitespace
M2 server/src/WinUiXaml.LanguageServer/XamlRename.cs:213-232 correctness ChangesElementNameResolution skips unresolved ElementName bindings (current is null), allowing silent capture on rename
M3 server/src/WinUiXaml.LanguageServer/XamlValidator.Document.cs:254-283 correctness RequiresExplicitResourceKey (WXAML0036) exempts keyless/targetless Style and flags implicit DataTemplate x:DataType
M4 server/src/WinUiXaml.LanguageServer/XamlValidator.Structure.cs:292-322 correctness, alternative-solution ValidateResourceValueType (WXAML0047) rejects Color-to-Brush StaticResource and skips dotted/Setter targets
M5 server/src/WinUiXaml.LanguageServer/XamlValidator.Structure.cs:324-350 correctness, alternative-solution, extension-ux ValidateBindTargetMember drops WXAML0048 on prefixed attached properties and false-positives on dotted event attributes
L1 server/src/WinUiXaml.LanguageServer/CompletionProvider.Classification.cs:145-184 correctness, test-coverage IsInsideOpenTagValue returns false when an open attribute value contains multiple '<' characters
L2 server/src/WinUiXaml.LanguageServer/CompletionProvider.ElementsAndAttributes.cs:1324-1340 extension-ux AddProjectTypeNames sets FilterText = type.Name while Label = itemPrefix + ":" + type.Name
L3 server/src/WinUiXaml.LanguageServer/XamlLanguageServer.Navigation.cs:93-124 correctness CollectScopedNameOccurrences walks outer template scopes even for non-ElementName dangling references
Details
## M1 server/src/WinUiXaml.LanguageServer/CompletionProvider.ElementsAndAttributes.cs:160-172
- Severity: medium
- Confidence: high
- Domain: correctness
- Finding: `IsResourceChildContext` resolves to the preceding closed sibling element when `<` is typed immediately after `/>` with no whitespace, failing to offer resource-specific completions.
- Evidence: `doc.Parsed.FindNode(Math.Max(0, ctx.ReplaceStart - 2))` hits the closing `>` of `<SolidColorBrush x:Key="A"/><|` and returns `false` on the first iteration because `enclosing.Span.Start < ctx.ReplaceStart - 1` is true for the closed sibling.
- Recommendation: Skip closed elements whose `Span.End <= ctx.ReplaceStart - 1` when walking `node.Parent`.
## M2 server/src/WinUiXaml.LanguageServer/XamlRename.cs:213-232
- Severity: medium
- Confidence: high
- Domain: correctness
- Finding: `ChangesElementNameResolution` ignores unresolved `{Binding ElementName=...}` references (`current is null`), allowing a rename in an enclosing scope to silently capture a previously unresolved `ElementName` binding.
- Evidence: Line 224 checks `(reference.Name == newName && current is not null && IsFoundFirst(doc, reference.Attribute, declaration, current, typeSystem))`. When `current` is `null`, renaming an outer element to `newName` passes validation and binds the previously unresolved reference without renaming or rejecting it.
- Recommendation: When `reference.Name == newName` and `current is null`, reject the rename if `declaration` is reachable from `reference.Attribute` via `EnumerateElementNameBindingTargets`.
## M3 server/src/WinUiXaml.LanguageServer/XamlValidator.Document.cs:254-283
- Severity: medium
- Confidence: high
- Domain: correctness
- Finding: `RequiresExplicitResourceKey` (`WXAML0036`) unconditionally exempts `<Style>` even when both `x:Key` and `TargetType` are absent, and flags `<DataTemplate x:DataType="...">` which supports implicit data-type keying in WinUI.
- Evidence: `RequiresExplicitResourceKey` returns `false` for all `Style` elements at line 282, while `TryGetResourceKey` returns `false` when `TargetType` is missing, so `<Style><Setter .../></Style>` gets no diagnostic; meanwhile `<DataTemplate x:DataType="local:Item">` without `x:Key` is flagged with `WXAML0036`.
- Recommendation: Only exempt `Style` when `TargetType` is present, and exempt `DataTemplate` when `x:DataType` is present.
## M4 server/src/WinUiXaml.LanguageServer/XamlValidator.Structure.cs:292-322
- Severity: medium
- Confidence: high
- Domain: correctness, alternative-solution
- Finding: `ValidateResourceValueType` (`WXAML0047`) rejects `<Color>` resources assigned to `Brush` properties (which completion offers) and skips dotted attached properties and `<Setter Value="{StaticResource ...}">`.
- Evidence: Lines 298-303 skip `attribute.Name.IsDotted` and call `FindAttributeMember` directly instead of `ResolveAttributeTargetType`, and lines 311-318 check `resourceType.SpecialType != SpecialType.None || XamlTypeSystem.IsAssignableTo(resourceType, target) || typeSystem.HasImplicitConversion(resourceType, target)`, which is false for `Windows.UI.Color` (`SpecialType.None`) on a `Brush` property (whereas `CompletionProvider.BindingsAndResources.cs:500-505` explicitly allows `Color` for `Brush`).
- Recommendation: Align `ValidateResourceValueType` with the `Color`-to-`Brush` rule in `CompletionProvider.BindingsAndResources.cs` and use `ResolveAttributeTargetType`.
## M5 server/src/WinUiXaml.LanguageServer/XamlValidator.Structure.cs:324-350
- Severity: medium
- Confidence: high
- Domain: correctness, alternative-solution, extension-ux
- Finding: `ValidateBindTargetMember` (`WXAML0048`) drops static-method diagnostics on prefixed attached properties and false-positives on owner-qualified event attributes (`<Button Button.Click="{x:Bind OnClick}" />`).
- Evidence: `attribute.Name.HasPrefix` returns early at line 331 while `ValidateStaticMemberChain` (`XamlValidator.BindPaths.cs:255-260`) suppresses `WXAML0005` on bare static methods assuming `ValidateBindTargetMember` will emit `WXAML0048`, leaving `local:Attached.Prop="{x:Bind local:Helpers.Join}"` with no diagnostic; meanwhile `FindAttributeMember(elementType, attribute.Name.LocalName)` returns `null` for dotted `Button.Click`, skipping the event exemption.
- Recommendation: Resolve dotted and prefixed attributes before checking whether the target is an event or property.
## L1 server/src/WinUiXaml.LanguageServer/CompletionProvider.Classification.cs:145-184
- Severity: low
- Confidence: high
- Domain: correctness, test-coverage
- Finding: `IsInsideOpenTagValue` returns `false` when an open attribute value already contains an earlier `<` character (`Text="a < b<|"`), and `SourcePageType` completion lacks a dedicated unit test.
- Evidence: `int previousLt = text.LastIndexOf('<', lt - 1);` stops at the earlier `<` inside the attribute string rather than the enclosing element's `<`.
- Recommendation: Scan forward from the enclosing tag opener and add `[InlineData]` coverage for multiple `<` in `AttributeCompletionTests.cs` as well as a `SourcePageType` test case.
## L2 server/src/WinUiXaml.LanguageServer/CompletionProvider.ElementsAndAttributes.cs:1324-1340
- Severity: low
- Confidence: high
- Domain: extension-ux
- Finding: `AddProjectTypeNames` sets `Label = itemPrefix + ":" + type.Name` with `FilterText = type.Name`, so typing the prefix in VS Code filters out the completion item.
- Evidence: Lines 1324-1338 set `Label = label` (`itemPrefix + ":" + type.Name`) and `FilterText = type.Name` (unlike `AddProjectElementTypes` at lines 312-320 where `Label = type.Name`).
- Recommendation: Match `AddProjectElementTypes` (`Label = type.Name`) or include the prefix in `FilterText`.
## L3 server/src/WinUiXaml.LanguageServer/XamlLanguageServer.Navigation.cs:93-124
- Severity: low
- Confidence: high
- Domain: correctness
- Finding: `CollectScopedNameOccurrences` resolves `declaration` via `FindElementNameBindingTarget` even when the cursor is on a non-`ElementName` reference inside a template.
- Evidence: Line 100 calls `XamlSemanticFacts.FindElementNameBindingTarget(doc, context, name, typeSystem)` unconditionally; if a template contains an unresolved `Storyboard.TargetName="Outer"`, occurrences switch to the outer `Outer` scope.
- Recommendation: Use `FindNamedElementInScope` unless `context` is on an `ElementName` argument or declaration.
Coverage notes
security: Checked iterative stack traversal and BasedOn HashSet cycle guard in XamlValidator.Structure.cs, parent-chain walks in XamlSemanticFacts.cs/XamlRename.cs, linear string scans in CompletionProvider.Classification.cs, and Roslyn SourceTree path checks in XamlTypeSystem.cs — no security issues found.
docs-and-samples: Checked README.md, docs/, server/, and .github/ for WXAML diagnostic tables or XAML completion docs — no doc drift found.
packaging: Checked SDK-style .csproj compile globs, Native AOT compatibility, .vscodeignore exclusions, and CI/release scripts — no packaging drift found.
|
|
||
| return XamlSemanticFacts.ResolveElementType(entry, typeSystem) is { } entryType && | ||
| !XamlSemanticFacts.IsStaticResourceElement(name, uri) && | ||
| !(typeSystem.Capabilities.Style is { } style && XamlTypeSystem.IsAssignableTo(entryType, style)); |
There was a problem hiding this comment.
Two edge cases in RequiresExplicitResourceKey (WXAML0036):
<Style>only has an implicit key whenTargetTypeis set (TryGetResourceKeyreturnstruewhenTargetTypeis present), so a<Style>with neitherx:KeynorTargetTypeis skipped by both branches even though WinUI rejects it.<DataTemplate x:DataType="local:Item">inside aResourceDictionarysupports implicit data-type keying without anx:Key, whichRequiresExplicitResourceKeycurrently flags withWXAML0036.
There was a problem hiding this comment.
Thanks. I confirmed both points against a real WinUI build (Windows App SDK 2.6.5):
- Keyless, targetless
<Style>: agreed and fixed in 48dcd5a. The compiler reports WMC0060 ("must have a Key attribute") and WMC0080 ("must specify … TargetType"). A Style is now only exempt from WXAML0036 when it has aTargetType. I added a test case. <DataTemplate x:DataType="local:Item">withoutx:Key: I'm keeping this one flagged. Building it givesWMC0060: Dictionary Item 'DataTemplate' must have a Key attribute. Implicit keying by data type is a WPF feature that WinUI doesn't support, so WXAML0036 matches the compiler here.
| if (resourceType.SpecialType != SpecialType.None || | ||
| target.SpecialType == SpecialType.System_String || | ||
| XamlTypeSystem.IsAssignableTo(resourceType, target) || | ||
| typeSystem.HasImplicitConversion(resourceType, target)) |
There was a problem hiding this comment.
In ValidateResourceValueType (WXAML0047), <Color x:Key="Accent">#FF0000</Color> resolves to Windows.UI.Color (SpecialType.None) with no C# implicit conversion to Brush, whereas resource completion in CompletionProvider.BindingsAndResources.cs (ThemeKeyMatchesTarget) explicitly offers Color resources for Brush-typed properties. Also consider using ResolveAttributeTargetType instead of bailing out on attribute.Name.IsDotted so attached properties and <Setter Value="{StaticResource ...}"> use the same target-type resolution.
There was a problem hiding this comment.
I looked into both parts and am leaving this check unchanged. The reasoning is below; I'm happy to revisit if you have a case that works at runtime.
- Color resource on a Brush property: the build accepts it because
StaticResourceis resolved at runtime, but I don't believe the assignment works there. AColoris a struct andBrushis a class, and WinUI's resource lookup doesn't convert between them. WinUI's owngeneric.xamldefines 150<Color>resources and never uses one directly on a Brush property; it always wraps them in aSolidColorBrush.ThemeKeyMatchesTargetin completion is unchanged from main. Its comment says Color keys are deliberately left unfiltered ("keep them conservative"), not that they're valid for Brushes. I haven't run an app to confirm the runtime failure, so if you have a working example I'll relax the rule. - Attached properties and
Setter Value: true, these aren't checked. That's a gap in coverage, not a false error, and covering them would grow this already large PR for little value. I'd prefer it as a follow-up if we want it.
| if (previousLt < 0 || previousGt > previousLt) | ||
| { | ||
| return false; | ||
| } |
There was a problem hiding this comment.
L1 (correctness, test-coverage): IsInsideOpenTagValue calls text.LastIndexOf('<', lt - 1), which stops at an earlier < inside the same quoted attribute value (e.g. <Button Text="a < b<|" />) rather than the enclosing element's <, returning false and allowing element completions inside the attribute value. Also consider adding a unit test in AttributeCompletionTests.cs for SourcePageType="|" project-type filtering and ranking.
There was a problem hiding this comment.
I added the SourcePageType test in 48dcd5a. It checks that only Pages are offered and that project pages are ranked first.
I'm not changing the <-inside-a-value case. A raw < inside an attribute value is invalid XML (it has to be written <), so Text="a < b<|" is already a broken document, and the tag scan would need extra handling just for it.
- WXAML0048/0044 resolve owner-qualified and xmlns-prefixed attributes, so Button.Click x:Bind is no longer flagged and local:Owner.Prop is checked. - Resource completion works when '<' directly follows a self-closing entry. - A Style needs x:Key unless it has a TargetType (WMC0060/WMC0080). - Rename refuses capturing an unresolved ElementName binding. - Only ElementName arguments look outside template namescopes for references, rename and F12. - Project type completion matches and filters on the prefix:Type label. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved issues allow completion inside attribute values, miss inherited TwoWay binding validation, emit runtime diagnostics in design-time subtrees, and suppress legal Name/x:Name completions on non-FrameworkElement resources.
4 open issues
What changed in this PR
Updates the WinUI XAML language server to better match compiler and runtime behavior, addressing diagnostic false positives, missed errors, and completion gaps tracked in #351, #352, #357, and #358.
Changes:
- Shares template-aware ElementName lookup across validation, completion, navigation, and rename, and accepts string-source x:Bind conversions.
- Adds structural, binding, and resource diagnostics; expands type completion and static x:Bind navigation.
- Adds unit and smoke coverage and updates integration expectations.
| File | Description |
|---|---|
test/xaml-integration/redteam-xbind-adversarial-authoring.test.js |
Adds the name required by the x:Load fixture. |
test/xaml-integration/redteam-x-type-and-static.test.js |
Expects WPF-only markup extensions to be absent from suggestions. |
test/fixtures/xaml/fixture/Helpers.cs |
Adds static binding and converter fixtures. |
server/test/WinUiXaml.LanguageServer.Tests/XamlValidatorTests.cs |
Covers new diagnostics and false-positive fixes. |
server/test/WinUiXaml.LanguageServer.Tests/XamlRenameTests.cs |
Tests cross-template references and rename safety. |
server/test/WinUiXaml.LanguageServer.Tests/XamlCodeActionsTests.cs |
Tests namespace imports for plain CLR classes. |
server/test/WinUiXaml.LanguageServer.Tests/MarkupExtensionCompletionTests.cs |
Covers static types, outer namescopes, and supported extensions. |
server/test/WinUiXaml.LanguageServer.Tests/BindingSymbolTests.cs |
Tests static x:Bind symbol resolution. |
server/test/WinUiXaml.LanguageServer.Tests/AttributeCompletionTests.cs |
Covers construction filtering, resources, imports, and completion contexts. |
server/test/lsp-smoke/smoke-core-scenarios.mjs |
Adds end-to-end language-server regression scenarios. |
server/src/WinUiXaml.Workspace/XamlTypeSystem.cs |
Adds construction eligibility and project-type discovery helpers. |
server/src/WinUiXaml.LanguageServer/XamlValidator.Structure.cs |
Implements structural, resource, and binding-member checks. |
server/src/WinUiXaml.LanguageServer/XamlValidator.Elements.cs |
Connects resource and binding checks; detects empty event handlers. |
server/src/WinUiXaml.LanguageServer/XamlValidator.Document.cs |
Detects resource entries missing required keys. |
server/src/WinUiXaml.LanguageServer/XamlValidator.cs |
Registers diagnostic codes and structural validation. |
server/src/WinUiXaml.LanguageServer/XamlValidator.BindPaths.cs |
Routes bare static methods to the dedicated diagnostic. |
server/src/WinUiXaml.LanguageServer/XamlValidator.Bindings.cs |
Broadens ElementName lookup and string-source conversions. |
server/src/WinUiXaml.LanguageServer/XamlSemanticFacts.cs |
Adds classic Binding lookup across enclosing template scopes. |
server/src/WinUiXaml.LanguageServer/XamlRename.cs |
Rejects renames that change ElementName resolution. |
server/src/WinUiXaml.LanguageServer/XamlLanguageServer.Navigation.cs |
Follows cross-template ElementName references. |
server/src/WinUiXaml.LanguageServer/XamlLanguageServer.CompletionAndResources.cs |
Resolves static x:Bind types and members for navigation. |
server/src/WinUiXaml.LanguageServer/CompletionProvider.ElementsAndAttributes.cs |
Expands resource and project-type completion and filters suggestions. |
server/src/WinUiXaml.LanguageServer/CompletionProvider.cs |
Suppresses element completion after the root closes. |
server/src/WinUiXaml.LanguageServer/CompletionProvider.Classification.cs |
Adds suppression for element completion inside quoted values. |
server/src/WinUiXaml.LanguageServer/CompletionProvider.BindingsAndResources.cs |
Updates markup suggestions, ElementName lookup, and static-type completion. |
Review effort: Balanced
| int previousLt = text.LastIndexOf('<', lt - 1); | ||
| int previousGt = text.LastIndexOf('>', lt - 1); | ||
| if (previousLt < 0 || previousGt > previousLt) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| char quote = '\0'; | ||
| for (int i = previousLt + 1; i < lt; i++) | ||
| { | ||
| char c = text[i]; | ||
| if (quote == '\0' && c is '"' or '\'') | ||
| { | ||
| quote = c; | ||
| } | ||
| else if (c == quote) | ||
| { | ||
| quote = '\0'; | ||
| } | ||
| } | ||
|
|
||
| return quote != '\0'; |
There was a problem hiding this comment.
This reproduces, but I'm not changing it in this PR. A raw < inside an attribute value is invalid XML (it has to be written <), so Content="a>b< is already a malformed document when completion fires. Fixing it properly needs a full scanner that tracks tags and quotes and skips comments, CDATA and processing instructions, which is a lot of code for a rare moment while typing. This is the same class of input as the earlier Text="a < b<" comment, which we also declined. The common cases (a < typed inside a value that contains no >) are still suppressed and covered by tests.
| // The compiler strips design-time elements together with their content. | ||
| if (element.Name is { } elementName && IsIgnorableName(elementName, element)) | ||
| { | ||
| continue; |
There was a problem hiding this comment.
This reproduces, but it matches how the validator already behaved on main, so I'm leaving it out of this PR. The existing element and document validators have always checked inside d: element subtrees; for example, <d:Grid><TextBlock Bogus="1"/></d:Grid> reports WXAML0003 on main. Only the new structure checks in XamlValidator.Structure.cs skip design-time subtrees. In practice, design-time markup is almost always attributes (d:DataContext, d:DesignWidth) rather than element subtrees containing resources or x:Bind. Excluding design-time subtrees from every validator consistently would be a cross-cutting change that deserves its own follow-up.
- WXAML0044 uses the nearest x:DefaultBindMode when an x:Bind omits Mode. - Name and x:Name are only mutually exclusive in completion on FrameworkElement, matching WXAML0039. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Nikola Metulev (nmetulev)
left a comment
There was a problem hiding this comment.
Thanks for this, Chiara! It's a big step forward for XAML IntelliSense. CI is green on the current head, and locally all 1083 server tests and npm run test:xaml-smoke pass. I also checked the other new diagnostics (WXAML0036–0044, 0047, 0048 and 0002) against a set of tricky but valid XAML and found no false alarms there.
I found two things I'd like fixed before merge. I confirmed both against the real language server and a real WinUI app built with winapp run.
Must fix
- WXAML0046 flags valid same-key
BasedOnstyles. A style that reuses an outer or built-in key (BasedOn="{StaticResource AccentButtonStyle}") is reported as "based on itself", and A→B→A with an outer A is reported as circular. Both work at runtime. - The #352 fix turned off a warning for bindings that crash. A string source now passes for any target type, so
Command="{x:Bind GreetingText}"(string → ICommand) no longer gets WXAML0030. The build succeeds and the app crashes at launch.
Non-blocking
3. Rename edge case with a shared resource template in a nested template. I filed #395 for it; a follow-up is fine.
4. The {x:Static} error has no replacement hint, and the hover text contradicts the new error. A cheap fix that's worth doing in the same pass.
Details are in the inline comments.
| var (key, span, target) = reference; | ||
| if (ReferenceEquals(target, style)) | ||
| { | ||
| diagnostics.Add(Diag(doc, span, SeverityError, InvalidBasedOnCode, | ||
| $"The style '{key}' cannot be based on itself.")); | ||
| return; | ||
| } |
There was a problem hiding this comment.
Must fix: this flags valid XAML whenever a style reuses a key defined in an outer scope.
TryGetBasedOnReference (line 288) starts the lookup at the style itself, so FindDeclaration returns the same <Style>. That happens even when the same key also exists in an outer Resources, in App.xaml, or in the framework theme dictionaries.
<Page.Resources>
<Style x:Key="AccentButtonStyle" TargetType="Button" BasedOn="{StaticResource AccentButtonStyle}">
<Setter Property="Padding" Value="20" />
</Style>
</Page.Resources>main: no diagnostic- this PR:
WXAML0046 The style 'AccentButtonStyle' cannot be based on itself.
The loop below has the same problem. With <Style x:Key="A"/> in Page.Resources and A→B→A in Grid.Resources, both styles get "The BasedOn chain … is circular."
The WinUI runtime supports this pattern on purpose. When a key is already being loaded, lookup continues up the chain (CResourceDictionary::TryLoadDeferredResource in Resources.cpp, whose comment says "we support cases where a style is based on another style with the same key in inherited resources"). I built all three styles into a real app and they ran correctly: the button got Padding=20 on top of the built-in accent background, and the inner style inherited FontSize=20.
Suggested fix: when the lookup resolves to the style itself (or to a style already in the chain), continue the lookup in scopes outside that style's dictionary. If nothing else is found in the file, stay silent, because the key may come from App.xaml, a merged dictionary or the theme resources. Only report a self-reference or cycle when the key provably can't resolve anywhere else.
| // The XAML compiler converts string sources with XamlBindingHelper.ConvertValue. | ||
| if (source.SpecialType == SpecialType.System_String) |
There was a problem hiding this comment.
Must fix: this relaxation is broader than #352 needs. With it, any string source is treated as assignable to any target, including targets that XamlBindingHelper.ConvertValue can't create from text.
<Button Command="{x:Bind GreetingText}" /> <!-- GreetingText is a string -->main:WXAML0030 The x:Bind result type 'string' is not assignable to 'ICommand'.- this PR: no diagnostic. The build also succeeds (the generated code calls
ConvertValue(typeof(ICommand), …)), and the app crashes at launch withArgumentException: The value cannot be converted to type ICommand.
ListView ItemTemplate="{x:Bind GreetingText}" (string → DataTemplate) lost its warning the same way.
Suggested fix: limit the exemption to target types that can actually be converted from text: value types and enums, plus non-interface framework classes like Brush, ImageSource and Uri, which are the #352 cases. Keep WXAML0030 for interfaces, templates and project classes. Adding [InlineData("Command", "Text")] to BindAssignment_StillReportsIncompatibleNonStringSources would lock this down.
| foreach (var reference in EnumerateElementNameReferences(doc, typeSystem)) | ||
| { | ||
| if (reference.Name == name && | ||
| !inScope.Contains(reference.Element) && | ||
| ReferenceEquals( | ||
| XamlSemanticFacts.FindElementNameBindingTarget(doc, reference.Attribute, name, typeSystem), | ||
| declaration)) | ||
| { | ||
| occurrences.Add((doc.RangeOf(reference.Span), false)); | ||
| } |
There was a problem hiding this comment.
Non-blocking, fine to handle in a follow-up (filed as #395).
This loop treats the namescope where a resource template is declared as the scope that hosts it. At runtime, WinUI resolves ElementName through the instantiated host instead. Take a shared <DataTemplate x:Key="ChildTemplate"> that binds ElementName=Source, used from inside an ItemTemplate that declares its own x:Name="Source". Renaming the page-level Source also rewrites the binding in the shared template. In a real app, the template showed "Row" before the rename and "Page" after it, with no warning. The full repro is in #395.
| var replacement = name.LocalName switch | ||
| { | ||
| "DynamicResource" => " Use ThemeResource or StaticResource instead.", | ||
| "Type" => " Use the type name directly instead.", | ||
| _ => string.Empty, | ||
| }; |
There was a problem hiding this comment.
Non-blocking suggestion: DynamicResource and x:Type get a replacement hint here, but x:Static gets none. The WinUI equivalent is a static x:Bind path, which this PR's new {x:Bind prefix:|} completion supports:
"Static" => " Use {x:Bind local:Type.Member} instead.",Related: the hover text in XamlDirectiveMetadata.cs:30-31 (not changed in this PR) still describes {x:Static} ("References a static field, property, or constant.") and {x:Type} as working features. So hovering the squiggle contradicts the new error. Changing those entries to say "WPF only, not supported in WinUI" would make the two consistent. It's a cheap fix and worth doing in the same pass.

Description
Fixes several XAML IntelliSense bugs reported against the WinUI language server: two false-positive errors, many constructs that build or run broken without a warning, and gaps or wrong suggestions in completion. Diagnostics now follow one rule: report only what the WinUI XAML compiler or runtime actually rejects. Each new check was confirmed against a real WinUI project build.
False positives fixed
{Binding ElementName=X}inside aDataTemplateorControlTemplatenow resolves to elements in enclosing scopes, matching the runtime. Validation, completion, F12, find references and rename all use the same lookup. Rename refuses any edit that would change which element an ElementName binding refers to. ([Bug]: ElementName binding inside a template is falsely reported as an error (WXAML0027) #351)x:Bindfrom astringsource to a non-string property (Brush, Uri, ImageSource, …) is no longer flagged WXAML0030, because the compiler converts it. ([Bug]: x:Bind from a string to a non-string property is falsely reported as an error (WXAML0030) #352)New diagnostics (#357)
x:Key(onlyStylemay be implicit)x:Type,x:Static,DynamicResource, with a replacement hint where one existsx:Nametogether withNameon a FrameworkElementx:Load/x:DeferLoadStrategywithoutx:NameClick="")Mode=TwoWayx:Bind to a read-only memberBasedOnStaticResourcewhose type cannot be assigned to the property (primitive values are skipped, since WinUI converts them)()Style/ControlTemplateTargetTypeDesign-time (
d:) markup is skipped.Completion (#358)
x:String/x:Double/x:Int32/x:Booleanand project classes such as converters and view models, adding thexmlnsautomatically. App, Window, and static classes are excluded.x:DataTypeandSourcePageTypelist project types first.SourcePageTypeonly offers Pages.TargetTypekeeps framework types first.{x:Bind prefix:|}offers types with static members, and hover/F12 work on both the type and the member of a static path.Nameandx:Nameare no longer offered together.x:Typeandx:Staticare removed from markup-extension suggestions.Usage Example
Related Issue
Fixes #351
Fixes #352
Fixes #357
Fixes #358
Type of Change
Checklist
Additional Notes
Validation, run locally after merging current
main:dotnet test server/test/WinUiXaml.LanguageServer.Tests -c Debug: 1080 passed.node server/test/lsp-smoke/smoke.mjs: passed. New scenarios for [Bug]: ElementName binding inside a template is falsely reported as an error (WXAML0027) #351/[Bug]: x:Bind from a string to a non-string property is falsely reported as an error (WXAML0030) #352/[Bug]: XAML diagnostics miss many constructs that fail the build or crash at runtime #357/[Bug]: XAML completion gaps and wrong suggestions #358 were added.test/xaml-integrationsuite was run through a headless harness against both this branch andmain. No test passes onmainand fails here. The real VS Code run is left to CI..\scripts\build-vsce.ps1was not run. No extension-host code,package.json, or packaging changed. Only the language server and its tests did.Limitations:
Sourcefile-existence check was dropped: the build already reports it, and linked or packaged files would have forced it to guess.x:Static/x:Typecompletion andx:Loadwere updated to match the new behavior.AI Description
This section is auto-generated by AI when the PR is opened or updated. To opt out, delete this entire section including the marker comments.