Conditional logic vs duplication in MVVM [closed] - wpf

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
We have a module with its Views, ViewModels and Models and a requirement came in to have an exact copy of the module, but part of the functionality has to be read-only.
The read-only mode should be turned on by a configuration parameter. The Model part is the same - it will use the same data sources.
I see two possible solutions to this problem:
Change the existing Views and ViewModels, by manipulating controls' interactivity based on the param.
Downsides of this approach is additional conditional logic. We're worried that if we do this, another requirement might come in, where we have to add more conditional logic. Upside - no duplication.
Another way is to split the existing view's into multiple components and assemble the regular module version and the read-only version using those components. We could disable interactivity on the View level in read-only versions and inherit from the ViewModel of the View which we're splitting from and override needed behaviour. The upside would be modularity. Downside - duplication, multiple places to maintain when new components are added in the future.
What's the preferred approach to solve problems like this?

This is a little simpler than you think.
The most elegant approach is to have a flag or value contained within the viewmodel which represents the editable state of the data (this could simply be a true/false flag, but I've also seen cases where it can be represented as an enum because there are multiple conditions or states).
Then within the view you can bind the control's IsEnabled or IsReadOnly properties to that value (using a converter if necessary to change the value to a boolean).

Obviously impossible to give a definitive answer without knowing all the specifics, but I generally take the view that if something is only required once, or maybe even twice, then I'll take the quickest and easiest route. In your case that would be to add conditional logic to the existing classes.
At the third change, I'll review and see if it needs to be split out into a separate entity. but more often than not the third (or even second) change never comes. Don't code for the future, YAGNI.

Related

What are the cons of a data binding framework?

I've seen many data binding frameworks, such as WPF, AngularJS(Javascript), JSTL(JSP).
They are trying to separate UI and Data completely.
However, one main problem is that it adds complexity. Sometime, you have to write a lot of extra code (for example to extend a view class) just for one line of UI code.
In modern applications, there are many transition animations when changing one UI element from one state to another state. When use data binding framework, it seems not easy.
Are there any other cons of using a data binding framework?
For example, to set focus on a text input, so complex in AngularJS, See:
How to set focus on input field?
All of the following refers to the WPF.
You have to write a lot of extra code (for example to extend a view class) just for one line of UI code.
With regard to the WPF, this is rare situation, you can give an example?
There are many transition animations when changing one UI element from one state to another state.
In WPF since version .NET 3.5 appeared VisualStateManager:
The VisualStateManager enables you to specify states for a control, the appearance of a control when it is in a certain state, and when a control changes states.
His goal - is to define the application state, and each state to do an action, such as an animation. In this situation Binding is not used as such.
When use data binding framework, it seems not easy.
I do not think it's disadvantage. Data Binding needed as you mentioned: separate UI and Data completely. In fact, the whole MVVM pattern is based on a powerful technology as Data Binding. This feature allows you to create an abstract connection between Model and View via ViewModel. And the key word is Data, everywhere where there is work with the data, it is better to use Data Binding.
Binding allows you to do many interesting things, such as Validation, Converters and much more. It is typically used for Binding properties, and nothing more. To work with the UI using other features like VisualStateManager, Triggers, DataTriggers, etc. and it is not difficult when you use it to its destination, just need to get used to.
The only downside - is that Binding can be used for other purposes, such as use of the Converter when you can not do without it. And yes, at first it may seem unusual, but I do not think that this a drawback, the same can be said about other technologies.
Even as a drawback can be said about the performance. If you assign a value directly or via Binding, assigning a value directly will be faster. But I think that the advantages of Bindings allow not pay much attention to it.

New to MVVM: how to workout the View [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I've just got 3 classes: Topic, Example and Exercise. Topic is the main class where both Example and Exercise is linked to. In my window (non-MVVM) I am populating a listbox with my topics, and upon selecting an item in the listbox where the topics are bound to, I am getting the ID of that topic and again populating 2 listboxes (for examples and exercises) related to that topic.
As I am new to MVVM and still trying to understand it, I am at lost on how to convert this to MVVM. Should I have 3 views (3 usercontrols?) for each 3 classes (models)? In my current setting they are all in 1 window.
This is entirely up to you.
How do you normally split state and behavior across classes? There is no 'extra' rule for that in MVVM.
Think of reuse and single responsibility. This is applicable for View, ViewModel and Model classes.
It is possible to compose a View, ViewModel and Model out of multiple classes.
One thing I learned is that although it is possible to reuse a ViewModel for multiple Views (in fact some introductions to MVVM state that as benefit) I found that in general Views tend to change after a couple of releases and you'll quickly need to create a separate ViewModel for each View. Again, this is not a requirement of MVVM; it is good old object orientation.

What's the use of WPF's DataBinding? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I know the whole point behind it, but at the end of the day, the only thing provided is a clean code, am I right?
The problem:
To perform a data bind, you'll have to do some stuff in code behind (set a dependency property), which sometimes may be clear, and sometimes not. Then you'll have to find out how the hell to access the values from your dependency property (the object you're trying to use). Then, ok, you spent some time deciding that you'll access it through ElementName or Ancestor or whatever (because you'll have to find out by yourself how this works, Microsoft's documentation on that is pretty lame, it's not straight forward).
Then, ok, you spent some time and now your data binding is working, except that is not. Because the class of the object you're binding to must implement INotifyPropertyChanged. Just that. Or not, because you'll have to assure that an event (OnPropertyChanged) must be triggered in order to update the values on your interface ... by sending as an argument a string containing THE NAME OF THE EFFING PROPERTY. That's as lame as JSF's way to access values (obliging the developer to have getters and setters exactly the way they want). An also, if you're building your software in layers, forget, you'll have to implement INotifyPropertyChange every-effing-where.
I'm writing this because I want to know if:
I'm doing everything wrong and that's why I don't get the point.
Is there a better solution to deal with this kind of stuff?
Am I the only one who thinks that it doesn't make any sense?
Before anyone asks: Yes, I understand that the event makes "some" sense, because there must be a way to know that the object changed. But I don't see much difference of using that or just calling an Update method every time I do anything in the interface. I hope you guys don't think I'm stupid for posting this ... I'm a pretty new programmer (3 years since my graduation began and 2 years working experience), but the lack of a better way to do that kind of stuff doesn't look like, for instance, Microsoft's ASP.NET MVC, which just works magically. I'm not asking for everything to be easy, just asking for a better documentation, and, I don't know, an easier (by easier I mean more straight-forward) way to do something that you're supposed to do when using the framework, something that is considered elegant.
I like turtles. I also love data binding. I recommend reading up on the MVVM pattern... it uses data binding to make it easy for you to run unit tests and keep your code organized/clean. Be sure to look at how the "DataContext" property is used in MVVM.
P.S. I don't think that using the name of the effing property in OnNotifyProperty is lame at all. What else would you use without adding dependencies or unneeded complexity?
P.P.S. Clean code is a very big effing deal.
That it is hard to learn does not change that it is a powerful technique, this covers about most of your rant.
You can resolve the property name from a lambda expression if you have an aversion to strings. The code for an extension method that does that is floating around somewhere on SO.
If you don't want to implement it everywhere implement it in one base-class.
If you want magic use an MVVM framework that does that. Caliburn for example hooks up controls and methods/properties without writing any binding code.
Bindings decouple components.

Change Tracking View Model: When/How to "Start Tracking"? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I have need of a view model that tracks changes so the user can see things visually change in response to edits and rollback portions. Right now, I "turn on" change tracking as the last step in the constructor for the view model (necessary, because sometimes the view models are constructed from templates or have defaulting logic that triggers PropertyChanged before construction is complete, erroneously leading one to think it's changed even before the user has done anything).
This has worked for the most part,
but with more complicated controls, bindings, and lack of controlling the order for various events in third-party products
and, a need to turn on change tracking after view model is built from a DTO returned from a service call (i.e. the model-model),
is there a better place to turn-on change tracking?
In an ideal MVVM implementation there's neither better nor alternative place, because you aren't likely to know when or how a view communicates with a view model. In fact, a view model shouldn't know anything about a view. A view might be a Silverlight UI or a console app, or a test mock-up, or whatever else. According to general thoughts then, constructor seems to be the only place where 'change tracking' should be disabled.
If you try following the MVVM strictly, you should accept your view models as main objects and views as secondary ones. I mean a view shouldn't introduce any logic that doesn't relate to the specific view implementation. It only displays the current view model state and communicates a user's actions to the view model. If it's true, then you won't need to turn change tracking off wherever except the constructor.
Of course, in the real world this might get rather difficult to follow. If you can't find another solution, you could introduce additional properties to the view model, e.g. IsViewInitialized, which would turn on 'change tracking', and make the view set the property as required.
But you'd better avoid this as long as possible. Such an approach increases coupling between Views and ViewModels which is against one of the main ideas of the MVVM pattern.
If you'd ask me in personal, my view models quite rarely have an alternative logic for the initialization steps and if they do, it's only in the constructors. And I usually don't 'turn off change tracking' but rather set some fields directly to get around the regular change tracking code that for most cases resides in property setters. But sometimes it's more convinient to trigger that logic for some properties even in a constructor.
Generally, there is no "right" or "wrong" place to handle change tracking.
But if you prefer to do it inside VM, your RaisePropertyChanged() method can accumulate list of changed properties (changesList). You should implement public (possibly virtual) method ApplyChanges(), that clears this list and saves data (if you post changes through network, add more checks so you don't send the same data over and over). Also, have public property bool IsChanged { get; }, that returns changesList.Any() -- you can use this property to bind your "Apply" buttons to.
For your case: in complex constructors, invoke ApplyChanges() to reset IsChanged state, and after complex controls are bound to your VM, also invoke ApplyChanges() - even if you know user didnt do anything yet.

Do you databind your object fields to your form controls?

Or do you populate your form controls manually by a method?
Is either considered a best practice?
Generally, if data binding business or DAL objects is possible, I would use it. The old axiom holds true: The most error-free and reliable line of code is often the one you didn't have to write. (Bear in mind, however, that you need to know exactly how that data binding occurs, what its overhead is, and you have to be able to trust the framework and your source objects to be error-free!)
You would, as others have mentioned, manually populate if you needed specific functionality not brought to bear directly by binding, or if there is an issue with data binding business/DAL objects (as occasionally happens with certain 3rd-party controls).
Well, it depends. I have tended to use databinding wherever I could - it is darn convenient, but on occasion, I'll populate them manually. Particularly, I find it useful with controls like the DataGridView to use databinding. It makes filtering quite simple.
It really depends from what you are trying to achieve.
Databinding is simple and powerful, but if you need more control or some kind of side effect, you can manually populate control from a method.
Personally, I start with a databinding first, than change it later if it is necessary.

Resources