Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid MVVM/data binding for small windows?

I've found view models to be very useful for splitting user interface and business logic code. However, I've also made the experience that for small, simple windows a view model class just adds a lot of additional code, effectively reducing maintainability instead of improving it.

Let me give you a simple, real-world example that I've had recently: A dialog window providing two (fixed-text) buttons and a customizable text block.

  1. Using plain old x:Name-based code-behind programming technique, this is a matter of a few lines of code (set the text, handle the two button clicks by returning a value and closing the window) -- clean and simple.

  2. Doing it the "recommended way", i.e., creating a view model class (implementing INotifyPropertyChanged or inheriting DependencyObject) and defining Commands requires an awful lot of code compared to the solution above (especially since there is no concise way to define "local variable + property + raise PropertyChanged" in VB) -- making the solution less readable and more error-prone.

So, currently I'm using the pragmatic approach of choosing between "plain old x:Name" and view model on a case-by-case basis. However, the wealth of blog/forum postings claiming that the view model should be used all the time makes me wonder whether I've overlooked something.

Did I overlook something?

like image 550
Heinzi Avatar asked Dec 30 '22 16:12

Heinzi


2 Answers

I'm all for MVVM, but the window you're describing can be implemented once and then filled as needed when you want to open one. So the ViewModel might look like this:

public SmallDialogTask
{
    string Title { get; set; }
    string Text { get; set; }
    string AcceptButtonLabel { get; set; }
    string RejectButtonLabel { get; set; }

    Command AcceptCommand { get; }
    Command RejectCommand { get; }
}

Implement this once and use inheritance to configure the various instances where you need it. As you can see from my example, this allows you to encode much more semantics into your class.

See also DRY, my question about MVVM dialogs and -- just for reference -- my blog post about MVVM.

like image 149
David Schmitt Avatar answered Jan 05 '23 18:01

David Schmitt


You can use data binding without defining a view model - and in most "small" windows there isn't mush logic - so you don't actually need change notification.

Just set DataContext = this and data-bind to properties of the window class.

Commands, on the other hand, don't have good simple version so I'll just use good old event handling.

(I also think that MVVM is overkill for a lot of not-so-small windows, but I'm obviously in the minority on that one)

like image 33
Nir Avatar answered Jan 05 '23 18:01

Nir