Conclusion: microsoft.toolkit.mvvm should be used carefully in WPF projects under the. Net framework.
Microsoft.toolkit.mvvm is the relay of MVVM light. Today, an outrageous compile time error occurred when using microsoft.toolkit.mvvm7.1.1 in the WPF project with the target framework of framework4.6.1, provided that it is opened Tools & gt; Options & gt; Environment & gt; Preview function & gt; New version of WPF XAML designer for net framework (restart required) 。 (Visual Studio 2019 version above 16.10)
Related links: https://docs.microsoft.com/zh-cn/visualstudio/xaml-tools/xaml-design-time-sample-data?view=vs -2019
The following classes are defined:
public class Class1 : Microsoft.Toolkit.Mvvm.ComponentModel.ObservableObject { }
Then use it in the XAML file:
<Window.Resources> <local:Class1 x:Key="bbb"/> </Window.Resources>
Error reported in red: Xdg004 cannot assign the specified value. Expected the following type: ‘object’ , As a result, the current XAML designer cannot be displayed normally, but it will run normally if the program is started.
Change the XAML code to:
<Window.DataContext> <local:Class1 x:Name="aaa"/> </Window.DataContext>
Error reporting in red: Xdg004 cannot assign the specified value. Expected the following type: ‘object’ Xdg004 attached property ‘name’ can only be applied to types derived from ‘obiect’, As a result, the current XAML designer cannot be displayed normally. If you start the program, it will run normally.
This mistake was outrageous, and then I corrected it Class1 Class, delete its parent class:
public class Class1 { }
The program did not report an error. Then I will Microsoft.toolkit.mvvm.componentmodel.observableobject as Class1 is the parent class of class and will Tools & gt; Options & gt; Environment & gt; Preview function & gt; The new version of WPF XAML designer for net framework (restart required) closes.
take Tools & gt; Options & gt; Environment & gt; Preview function & gt; After the new version of WPF XAML designer for net framework is closed (restart is required), the program will no longer report errors.
At this time, I created another WPF project based on. Net 5, and the error disappeared. Guess because The frequently used nullable reference type in microsoft.toolkit.mvvm.componentmodel.observableobject causes Tool & gt; Options & gt; Environment & gt; Preview function & gt; The new version of WPF XAML designer for net framework (restart required) turns off this function exception. This feature is only available in c#8.0, and the framework supports c#7.3 at most. Turn off this function to solve the problem. But I don’t know if there are other hidden dangers?Microsoft.toolkit.mvvm is a very new MVVM framework. It is safer to use MVVM light for WPF projects based on. Net framework.
Related links: https://docs.microsoft.com/zh-cn/windows/communitytoolkit/mvvm/introduction