I just started studying CommunityToolkit.Mvvm
package (aka MVVM Toolkit) and reading the introduction documentation it seemed like it would work for VB.NET as well:
Introduction to the MVVM Toolkit - Community Toolkits for .NET
But I wrote a VB.NET test project (I installed the CommunityToolkit.Mvvm NuGet package on the latest stable version 8.2.2) and it looks like it's not automatically generating the observable code:
Imports CommunityToolkit.Mvvm.ComponentModel
Partial Public Class MyViewModel : Inherits ObservableObject
<ObservableProperty>
Private id As Integer
<ObservableProperty>
<NotifyPropertyChangedFor(NameOf(FullName))>
Private firstName As String
<ObservableProperty>
<NotifyPropertyChangedFor(NameOf(FullName))>
Private lastName As String
Public ReadOnly Property FullName As String
Get
Return $"{firstName} {lastName}"
End Get
End Property
End Class
So, I tried doing exactly the same in a C# project and it worked:
using CommunityToolkit.Mvvm.ComponentModel;
internal partial class MyViewModel : ObservableObject
{
[ObservableProperty]
private int id;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(FullName))]
private string firstName;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(FullName))]
private string lastName;
public string FullName => $"{firstName} {lastName}";
}
So, does the automatic code generation for ObservableObject
and ObservableProperty
work for VB.NET or not?
I didn't find any mention of VB.NET in the documentation, other than that excerpt I mentioned in the question, but I did a search now in the source code of the CommunityToolkit.Mvvm
package (GitHub - CommunityToolkit/dotnet: .NET Community Toolkit) and it seems that code generation really only works for C#:
namespace CommunityToolkit.Mvvm.SourceGenerators;
[Generator(LanguageNames.CSharp)]
public sealed partial class ObservablePropertyGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// [ ... ]
if (!context.SemanticModel.Compilation.HasLanguageVersionAtLeastEqualTo(LanguageVersion.CSharp8))
{
return default;
}
// [ ... ]
}
}
Note the attribute used for the class, Generator(LanguageNames.CSharp)
, and the section that checks that the language version is at least C# 8, Compilation.HasLanguageVersionAtLeastEqualTo(LanguageVersion.CSharp8)
.