CommunityToolkit / MVVM-Samples

Sample repo for MVVM package
Other
1.15k stars 224 forks source link

How to Implement Interface when using ObservableProperty & RelayCommand attributes? #100

Open roysurles opened 2 years ago

roysurles commented 2 years ago

Hello,

Is there a sample showing how to implement an interface when using ObservableProperty & RelayCommand attributes? How would one implement the ISampleViewModel interface for SampleViewModel?

public partial class SampleViewModel : ObservableObject { [ObservableProperty] ObservableCollection items;

[RelayCommand]
void IncrementCounter()
{
}

}

public interface ISampleViewModel { ObservableCollection Items { get; set; }

void IncrementCounterCommand();

}

mikechristiansenvae commented 2 years ago

If the interface's IncrementCounterCommand was actually called IncrementCounter, then I see no reason why it wouldn't work in the normal way.

[ObservableProperty] ObservableCollection items; would generate a property ObservableCollection Items { get; set; }, which matches the interface.

You also have the IncrementCounter method, which matches the interface. Note, you need to use the public access modifier.

public interface ISampleViewModel
{
    ObservableCollection Items { get; set; }
    void IncrementCounter();
}

public partial class SampleViewModel : ObservableObject, ISampleViewModel
{
    [ObservableProperty]
    ObservableCollection items;

    [RelayCommand]
    public void IncrementCounter()
    {
    }
}

Or, if you didn't want to make any changes to the interface, you could implement it explicitly. Note that when implementing an interface member explicitly, you can't use access modifiers.

public interface ISampleViewModel
{
    ObservableCollection Items { get; set; }
    void IncrementCounterCommand();
}

public partial class SampleViewModel : ObservableObject, ISampleViewModel
{
    [ObservableProperty]
    ObservableCollection items;

    [RelayCommand]
    void IncrementCounter()
    {
    }

    void ISampleViewModel.IncrementCounterCommand()
    {
        this.IncrementCounter();
    }
}