You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在XAML中指定嵌套ResourceDictionary类型以解决XLS0521绑定错误

Fixing XLS0521 "Type 'DictionaryEntry' is not a collection" in XAML for Grouped Localization Resources

I’ve run into this exact IntelliSense quirk before—it’s super frustrating because your code works perfectly at runtime, but the editor keeps throwing false errors. The root issue is that Visual Studio’s IntelliSense can’t properly infer that your nested ResourceDictionary instances (like Group1 and Group2) are dictionary types; instead, it incorrectly treats them as DictionaryEntry objects, which don’t support the nested indexer syntax you’re using.

Here are two reliable fixes to make the error go away while keeping your localization structure intact:

Option 1: Explicit Type Casting in Binding Paths

Tell IntelliSense exactly what type to expect from the [Group1]/[Group2] indexer by adding an explicit type cast to the binding path. This overrides the incorrect type inference:

<ContextMenu DataContext="{DynamicResource Strings}">
  <MenuItem Header="{Binding Path=(ResourceDictionary)[Group1][Field1]}" />
  <MenuItem Header="{Binding Path=(ResourceDictionary)[Group1][Field2]}" />
  <MenuItem Header="{Binding Path=(ResourceDictionary)[Group1][Field3]}" />
</ContextMenu>

The (ResourceDictionary) cast clarifies that the value returned by [Group1] is a ResourceDictionary, not a DictionaryEntry, so IntelliSense recognizes that the nested [Field1] indexer is valid.

Option 2: Bind Directly to Nested Resource Dictionaries

Since you’ve already merged TranslationItems1.xaml into your UserControl’s resources, you can reference Group1 and Group2 directly as static resources. This bypasses the nested path inference issue entirely and makes your XAML cleaner:

Simplified ContextMenu Binding

Set the DataContext of the ContextMenu directly to the grouped resource dictionary:

<Button>
  <Button.ContextMenu>
    <ContextMenu DataContext="{StaticResource Group1}">
      <MenuItem Header="{Binding Path=[Field1]}" />
      <MenuItem Header="{Binding Path=[Field2]}" />
      <MenuItem Header="{Binding Path=[Field3]}" />
    </ContextMenu>
  </Button.ContextMenu>
</Button>

Alternative: Per-MenuItem Source

If you prefer to keep a shared data context, you can reference the grouped dictionary in each binding’s Source property:

<ContextMenu>
  <MenuItem Header="{Binding Source={StaticResource Group1}, Path=[Field1]}" />
  <MenuItem Header="{Binding Source={StaticResource Group1}, Path=[Field2]}" />
</ContextMenu>

Both options eliminate the XLS0521 error in IntelliSense while maintaining the exact same runtime behavior. Option 2 is my go-to for readability, but Option 1 works great if you want to stick close to your original binding structure.

内容的提问来源于stack exchange,提问作者Interminable

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:09:24