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

74 views Asked by At

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:

//[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();
        }
    }
}
1

There are 1 answers

2
Julian On BEST ANSWER

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.