Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
roysurles opened this issue Aug 23, 2022 · 1 comment

Comments

@roysurles
Copy link

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
Copy link

mikechristiansenvae commented Sep 12, 2022

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants