DEV Community

Brandon Weaver
Brandon Weaver

Posted on

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.

Top comments (0)