WPF绑定时VS IntelliSense不提示MVVM工具包源生成属性问题咨询
WPF使用MVVM Community Toolkit时XAML绑定IntelliSense不提示源生成属性问题
问题复现
使用MVVM Community Toolkit开发WPF应用时,XAML数据绑定场景下存在以下现象:
- 为ViewModel中手动实现的属性配置绑定时,IntelliSense可正常弹出属性补全提示
- 为通过
[ObservableProperty]特性触发源生成器生成的公开属性配置绑定时,补全列表无对应提示项 - 手动输入完整正确的源生成属性名后,鼠标悬停在属性名上可正常识别属性类型,说明IntelliSense并非完全无法检测到该成员
复现代码如下:
- ViewModel代码:
public partial class SimplisticViewModel : ObservableObject { [ObservableProperty] private int sourceGeneratedProperty; private float handmadeProperty; public float HandmadeProperty { get => handmadeProperty; set => SetProperty(ref handmadeProperty, value); } }
- XAML界面代码(已将DataContext设置为上述ViewModel实例):
<Window x:Class="WPFEFTest.TestWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WPFEFTest" mc:Ignorable="d" Title="TestWindow" Height="450" Width="800"> <Window.DataContext> <local:SimplisticViewModel/> </Window.DataContext> <StackPanel> <TextBox Text=""/> </StackPanel> </Window>
该问题并非错误绑定私有字段导致,
[ObservableProperty]特性会自动生成符合绑定要求的公开属性,生成的属性代码结构如下:
public partial class SimplisticViewModel { [global::System.CodeDom.Compiler.GeneratedCode("Microsoft.Toolkit.Mvvm.SourceGenerators.ObservablePropertyGenerator", "7.1.0.0")] [global::System.Diagnostics.DebuggerNonUserCode] [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public int SourceGeneratedProperty { get => sourceGeneratedProperty; set { if (!global::System.Collections.Generic.EqualityComparer<int>.Default.Equals(sourceGeneratedProperty, value)) { OnPropertyChanging(global::Microsoft.Toolkit.Mvvm.ComponentModel.__Internals.__KnownINotifyPropertyChangedOrChangingArgs.SourceGeneratedPropertyPropertyChangingEventArgs); sourceGeneratedProperty = value; OnPropertyChanged(global::Microsoft.Toolkit.Mvvm.ComponentModel.__Internals.__KnownINotifyPropertyChangedOrChangingArgs.SourceGeneratedPropertyPropertyChangedEventArgs); } } } }
解决方案
- 升级Visual Studio 2022至17.3及以上版本。旧版本XAML设计器的IntelliSense模块未完整适配Roslyn源生成器输出,17.3版本开始正式加入对源生成成员的XAML绑定补全支持。
- 升级项目引用的MVVM Community Toolkit至8.0及以上版本。7.x版本的源生成器未输出IntelliSense识别所需的完整设计时元数据,升级完成后重新生成项目即可正常触发提示。
- 若升级后仍存在不提示的问题,按以下步骤清除设计时缓存:
- 关闭所有运行中的Visual Studio实例
- 删除项目根目录下的
.vs隐藏文件夹,以及项目下的bin、obj文件夹 - 重新打开项目,等待NuGet包还原和项目初始化完成后,重新生成一次解决方案
- 临时兼容方案:编写绑定路径时,输入属性名前几个字符后按下
Ctrl+J手动触发IntelliSense补全列表,多数场景下可强制刷出源生成的属性项。
内容的提问来源于stack exchange,提问作者Petrusion
相关产品推荐
相关产品推荐

