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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

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

Okay