I recently tested the WPF UI library (https://wpfui.lepo.co/). I created a sample project, and that project targeted .NET 6.0. The sample project contained some basic Models and ViewModels, and in those files I found properties declared using the [ObservableProperty]
attribute. I really liked how that reduced the amount of code needed for simple properties, so I wanted to use that for an existing project which targets .NET Framework 4.7.2.
But I don't know how or if it is even possible. Existing information that I find online is very confusing, but the accepted answer to this question sounds like it is possible: Roslyn Source Generator not generating any source in a .net framework 4.7.2
I tried the following, but the application won't build:
using CommunityToolkit.Mvvm.ComponentModel;
namespace MatlogUtility
{
public partial class HeatListEntry : ObservableObject
{
[ObservableProperty]
private int? heatListId;
}
}
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Threading.Tasks;
using System.Windows;
using MatlogUtility.Models;
namespace MatlogUtility
{
public static class SqlQueries
{
public static List<HeatListEntry> GetHeatList()
{
List<HeatListEntry> heatList = new List<HeatListEntry>();
string queryString = "SELECT a as heatListId FROM someTable;";
using (SqlConnection connection = new SqlConnection(Globals.ConnectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
var reader = command.ExecuteReader();
try
{
while (reader.Read())
{
heatList.Add(new HeatListEntry
{
HeatListId = reader["heatListId"] == DBNull.Value ? null : (int?)reader["heatListId"]
});
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
return heatList;
}
}
}
The error list shows that 'HeatListEntry' does not contain a definition for HeatListId'
I also tried installing a bunch of NuGet-packages related to 'Roslyn', for example Microsoft.CodeAnalysis.CSharp and Microsoft.CSharp, but it still doesn't work.
Is what I am trying to do even possible? Thanks in advance, any pointers are appreciated!
CodePudding user response:
I also got into the same issue. It seems MVVM Source Generators don't support older .net frameworks (till 4.8). I changed my project framework from 4.8 to .net 6 and it worked fine.
You can also try, Upgrade a WPF App to .NET 6 with the .NET Upgrade Assistant