Skip to content

Fix XAML IntelliSense false positives, missing diagnostics, and completion gaps - #380

Open
Chiara Mooney (chiaramooney) wants to merge 8 commits into
mainfrom
chiaramooney-fix-xaml-intellisense-bugs-ddc
Open

Chiara Mooney (chiaramooney) wants to merge 8 commits into
mainfrom
chiaramooney-fix-xaml-intellisense-bugs-ddc

Conversation

@chiaramooney

@chiaramooney Chiara Mooney (chiaramooney) commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

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

New diagnostics (#357)

Code Catches
WXAML0036 Resource dictionary entry without x:Key (only Style may be implicit)
WXAML0037 WPF-only x:Type, x:Static, DynamicResource, with a replacement hint where one exists
WXAML0038 Element that cannot be created (abstract, or no public parameterless constructor)
WXAML0039 x:Name together with Name on a FrameworkElement
WXAML0040 Text content in an element whose content must be a UIElement
WXAML0041 Property set twice (attribute, property element, or implicit content)
WXAML0042 x:Load / x:DeferLoadStrategy without x:Name
WXAML0043 Empty event handler (Click="")
WXAML0044 Mode=TwoWay x:Bind to a read-only member
WXAML0046 Self-referencing, circular, or incompatible BasedOn
WXAML0047 StaticResource whose type cannot be assigned to the property (primitive values are skipped, since WinUI converts them)
WXAML0048 x:Bind to a method without ()
WXAML0002 Unknown Style/ControlTemplate TargetType

Design-time (d:) markup is skipped.

Completion (#358)

  • Element and resource completion only offers types that can actually be created. Resource dictionaries also offer x:String/x:Double/x:Int32/x:Boolean and project classes such as converters and view models, adding the xmlns automatically. App, Window, and static classes are excluded.
  • x:DataType and SourcePageType list project types first. SourcePageType only offers Pages. TargetType keeps 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.
  • Name and x:Name are no longer offered together.
  • No completion pops up inside an open attribute value or after the root element closes.
  • x:Type and x:Static are removed from markup-extension suggestions.

Usage Example

<Grid x:Name="Root">
  <ListView>
    <ListView.ItemTemplate>
      <DataTemplate>
        <!-- Before: WXAML0027 "Root not found". After: no error; F12 goes to the Grid. -->
        <TextBlock Text="{Binding Tag, ElementName=Root}" />
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>
  <!-- Before: no diagnostic. After: WXAML0042 'x:Load' requires the element to have an x:Name. -->
  <Button x:Load="False" />
</Grid>

Related Issue

Fixes #351
Fixes #352
Fixes #357
Fixes #358

Type of Change

  • 🐛 Bug fix
  • ✨ New feature
  • 🧪 Test update

Checklist

  • New tests added for new functionality (if applicable)
  • Tested locally on Windows (if applicable)

Additional Notes

Validation, run locally after merging current main:

Limitations:

  • Code WXAML0045 is intentionally skipped. A planned ResourceDictionary Source file-existence check was dropped: the build already reports it, and linked or packaged files would have forced it to guess.
  • Integration test expectations for x:Static/x:Type completion and x:Load were 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.

…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 <[email protected]>
- 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 <[email protected]>
- 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 <[email protected]>
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 <[email protected]>
…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 <[email protected]>
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 <[email protected]>
@github-actions

github-actions Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

VSIX Build

Artifact Baseline Current Delta
VS Code Extension (VSIX) 72.47 MB 72.53 MB 📈 +66.0 KB (+0.09%)

Updated 2026-11-23 21:13:53 UTC · commit 48dcd5a · workflow run

@chiaramooney
Chiara Mooney (chiaramooney) marked this pull request as ready for review November 13, 2026 17:33

@Jaylyn-Barbee Jaylyn Barbee (Jaylyn-Barbee) left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Two edge cases in RequiresExplicitResourceKey (WXAML0036):

  1. <Style> only has an implicit key when TargetType is set (TryGetResourceKey returns true when TargetType is present), so a <Style> with neither x:Key nor TargetType is skipped by both branches even though WinUI rejects it.
  2. <DataTemplate x:DataType="local:Item"> inside a ResourceDictionary supports implicit data-type keying without an x:Key, which RequiresExplicitResourceKey currently flags with WXAML0036.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks. I confirmed both points against a real WinUI build (Windows App SDK 2.6.5):

  1. 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 a TargetType. I added a test case.
  2. <DataTemplate x:DataType="local:Item"> without x:Key: I'm keeping this one flagged. Building it gives WMC0060: 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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

  1. Color resource on a Brush property: the build accepts it because StaticResource is resolved at runtime, but I don't believe the assignment works there. A Color is a struct and Brush is a class, and WinUI's resource lookup doesn't convert between them. WinUI's own generic.xaml defines 150 <Color> resources and never uses one directly on a Brush property; it always wraps them in a SolidColorBrush. ThemeKeyMatchesTarget in 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.
  2. 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;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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 &lt;), 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 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants