DEV Community

Brandon Weaver
Brandon Weaver

Posted on

1 3

Separation of Concerns in MVVM View-Model

I'd like to figure out what the convention is (if any) for separating form/view logic from a view-model. I will typically create a controls folder for each view-model which contains classes which directly relate to elements of the form/view.

For example

ViewModels
    Controls
        SomeViewModel
           Button1Controls.cs
    SomeViewModel.cs
Enter fullscreen mode Exit fullscreen mode

Within Button1Controls.cs

public bool IsActive
{
    get { return this._isActive; }
    set
    {
        this._isActive = value;
        this.Background = value ? "#F00" : "#0F0";
        this.OnPropertyChanged(nameof(this.IsActive));
    }
}

public string Background
{
    get { return this._background; }
    set
    {
        this._background = value;
        this.OnPropertyChanged(nameof(this.Background));
    }
}
Enter fullscreen mode Exit fullscreen mode

Then, within SomeViewModel.cs

public Button1Controls Button1Controls { get; set; }

public SomeViewModel()
{
    this.Button1Controls.IsActive = false;
}

public void Button1Click()
{
    this.Button1Controls.IsActive = !this.Button1Controls.IsActive;
}
Enter fullscreen mode Exit fullscreen mode

While this approach works well enough, I can't help but think that there are better conventions. I was hoping that some of you would be able to explain your strategies.

I used to just leave all of this logic in the view-model, but that quickly becomes a mess. I've since developed this approach without having found a 'proper' solution, so I look forward to hearing from all of you.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay