MVVM-Samples icon indicating copy to clipboard operation
MVVM-Samples copied to clipboard

How to Implement Interface when using ObservableProperty & RelayCommand attributes?

Open roysurles opened this issue 2 years ago • 1 comments

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();

}

roysurles avatar Aug 23 '22 18:08 roysurles

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

mikechristiansenvae avatar Sep 12 '22 15:09 mikechristiansenvae