Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I am having an issue with using Source Generator from the Community.Toolkit.MVVM in a multi tiered application

I am creating a multi-tiered WPF application using Microsoft’s Community Toolkit. My issue is that I want to use the Source Generators from the toolkit but that requires the ViewModel be in a partial class. So, for example, the View and ViewModel below works as shown. How do I do the same thing when my ViewModel needs to be a partial class instead of a public one?

View:

<Window x:Class="PlantWorks.FirstPart.MainView"
        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:v="clr-namespace:PlantWorks.FirstPart"
        xmlns:vm="clr-namespace:PlantWorks.Biz.FirstPart;assembly=PlantWorks.Biz"
        mc:Ignorable="d"
        Title="MainView" Height="450" Width="800">

    <Window.DataContext>
        <vm:MainViewModel />
    </Window.DataContext>

    <Grid>
        <TextBlock Text="{Binding SampleText}" FontSize="24" />
    </Grid>
</Window>

ViewModel:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

//[ObservableObject]
public class MainViewModel : ObservableObject
{
    string sampleText = "Hello World";
    //[ObservableProperty] private string sampleText = "Hello World!!!";
    public string SampleText
    {
        get => sampleText;
        set
        {
            if (sampleText == value)
            {
                return;
            }

            sampleText = value;
            OnPropertyChanged();
        }
    }
}

>Solution :

Your ViewModel can be public partial class MainViewModel : ObservableObject:

public partial class MainViewModel : ObservableObject
{
    [ObservableProperty] private string sampleText = "Hello World!!!";
}

The Source Generators generate the other part(s) of the class.

You don’t need the [ObservableObject] attribute.

You can still reference the ViewModel in your XAML as you have it already.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading