What's with empty code-behinds? - wpf

I understand the benefit to unit testing of preferring the view-model over the code-behind. However, I cannot understand the obsession with achieving completely empty code-behinds. At compile time, the code behind and the XAML are combined, so they are actually the same thing. I, to, love using XAML due to its declarative nature which is very cool. But is there actually any practical reason for insisting that all view-related code be XAML rather than C#?

There are also some benefits in taking advantage of what Blend can do at design-time with XAML but that's really more of a XAML vs (the same code) in code-behind argument. For the no code-behind argument as it relates to MVVM the real goal, as you've pointed out, is to get code moved into classes like ViewModels that can be tested and reused. As with many things, this often gets taken to the extreme and people end up insisting that there never be any code-behind when what is really needed is to have no business logic in code-behind, disregarding that there is also often UI logic too.
XAML is very rich and allows you to do a lot declaratively but there are still UI specific things (i.e. event handlers, some animation handling) that can't be done without using some code. You can usually manage to move this code to some place other than the code-behind by using things like custom controls, attached properties, etc. but if you're not getting any reuse benefits out of doing that it's probably just better to use the code-behind to do that UI logic instead.
Patterns like MVVM are general guiding principles, not a set of strict rules to be obsessively adhered to - those are called programming languages. :)

On good reason is that with WPF and XAML, Microsoft aim to keep separated the graphical and coding jobs. In this way, developer and UI designer can work easilly.

It's all about testability. It's hard (nigh impossible) to unit test your code behinds. With MVVM, you can create test harnesses that fully test your Model and ViewModel.
That being said, I'm a fan of being pragmatic. Some UI events are a bear to set up using Commands, and for those, I'll sometimes drop down into the codebehind.

The view model is the code-behind for the XAML. At least, that's how I think of it. And it's a code-behind file that can be tested without the XAML.
On the other hand, as Ben Johnson might have put it, no man but a fool ever implemented drag and drop in the view model.

Related

Is it possible to do in XAML part like as all i have done in code behind part?

I Mean can I do all operation in XAML with out using code behind.
The idea behind XAML was to separate presentation from business logic. Mixing those two concepts in the same file would be bad. Also writing C#/VB.NET code in a XML file could quickly turn into a nightmare. With the MVVM pattern you don't even need to setup explicitly the event handlers in the XAML. Not to mention the unit testability and maintainability of the application. Simply put: use the right gun for the right task.
Yes you can. Except if you need some UI logic. for exa if you want to do some thing particular when some event get fired from UI.

What is the real advantage of keeping code out of the XAML code behind?

There is a lot of effort in the Silverlight community to keep a XAML's code behind file as free of code as possible. What is the real motivation behind this?
For example, what is the advantage of using a command instead of an event handler? If I have
<Button x:Name="SaveButton" Content="Save" Click="SaveButton_Click" />
...
private void SaveButton_Click(object sender, RoutedEventArgs e) {
_myViewModel.SaveChanges();
}
Then why is this prefered?
<Button x:Name="SaveButton" Content="Save" Command="{Binding SaveCommand}" />
Where obviously the SaveCommand in my view model is effectively going to invoke SaveChanges().
This can lead to situations where the view is 100% XAML, even instantiating the view model in XAML, and the connections between the view and view model are completely done through binding. Sure it's clean, but what else is it? Flexible? Why? the view still needs to work with the proper ViewModel, so if the connection between the two exists and is implicit, why not make it more explicit? It also has the disadvantage of losing compile time support. If I hook my button up to an event handler that doesn't exist, the compiler will tell me. It won't if I bind to a non-existent command.
There is a lot of effort in the
Silverlight community to keep a XAML's
code behind file as free of code as
possible. What is the real motivation
behind this?
I would say that people who want the code behind "as free of code as possible" are those who have jumped on the MVVM bandwagon without really getting the point. (Either that or you have misinterpreted their point).
The point is not to keep the code-behind free of code, but to make sure that the View is only responsible for visual presentation. That fact that many visual aspects can be defined declaratively means there is less code in the code-behind, but it does not mean you should hesitate to write code-behind where you feel it is necessary and does not transgress outside the view's responsibilities.
what is the advantage of using a
command instead of an event handler?
A Command offers at least two capabilities that an event handler doesn't. Some WPF controls are aware of the CanExecute property of the Command, so for example a button can be disabled when the command is not available to execute. Also the designer and binding framework are Command aware.
If you just want to call a method on a button press there is no great advantage to using Commands instead of just calling the method from an event handler. So don't be afraid to use this approach. (A third approach, which favours designer over programmer, is to use the CallMethodAction from Blend 4).
It makes unit testing and / or TDD easier. By using MVVM and commanding, I can essentially build my view model and commands TDD style and have most of the view logic tested without actually having the XAML view at all.
There are probably many arguments you might hear for it but pragmatically there is only one, testability. A ViewModel delivers little unless you build a unit test for it, which in turn implies that you would need to create the ViewModel in such a way that you can unit test it, using techniques such as dependency injection, IoC, blah, blah, etc, etc.
The result is that unit tests can cover a larger part of your applications code than you could achieve had you kept the UI code more integrated.
I'm not necessarily recommending it, to do it properly takes considerable design effort and forethought. Hence the costs in building such an approach are quite high, however, the savings of the increased quality may well offset those costs.
The main advantage I see with the command is when you have the dual requirement of executing an action and validating that the action can execute (i.e. context). In other words, if you are simply linking the click with a straight method call, I agree, I see no advantage either. If the click should be conditioned, however, and the button disabled based on context, then the binding facilitates this through the CanExecute property.
This way, instead of having to worry about controls in the view (i.e. having the logic that says "find this control, and set it to disabled because we can't execute it right now) we can create a command and simply ensure that can execute returns false. This is testable independent of the view and once you do bind it, the binding itself takes care of managing the control's enabled property.

What are the real-world benefits of declarative-UI languages such as XAML and QML?

I'm currently evaluating QtQuick (Qt User Interface Creation Kit) which will be released as part of Qt 4.7. QML is the JavaScript-based declarative language behind QtQuick.
It seems to be a very powerful concept, but I'm wondering if anybody that's made extensive use of other, more mature declarative-UI languages like XAML in WPF or Silverlight can give any insight into the real-world benefits that can be gained from this style of programming. Various advantages are often cited:
Speed of development
Forces separation between presentation and logic
Better integration between coders and designers
UI changes don't require re-compilation
Also, are there any downsides? A few potential areas of concern spring to mind:
Execution speed
Memory usage
Added complexity
Are there any other considerations that should be taken into account?
(Updated)
The misconception with XAML is that it's not compiled. It is indeed compiled down to BAML a binary pre-tokenized XAML. Apparently there was a IL compiled version of XAML too called CAML. The OP pointed me to this good article explaining what XAML/BAML and CAML are.
Anyway, to the question why to use it:
XAML is simply a Serialization Format for C# objects that it is particularly well suited to describe hierarchical object structures, like found in WPF GUIs.
What WPF helps you do is write less boring C# code like this:
var grid = new Grid();
grid.Content.add(new TextBlock() {Text = "Hello"});
grid.Content.add(new TextBlock() {Text = "World"});
and just express it in a more readable way like this:
<Grid>
<TextBlock Text="Hello">
<TextBlock Text="World">
</Grid>
Since WPF object nesting (putting stuff inside other objects) can get very deep, WPF makes it much easier to read than the resulting C# code.
As for separation of concerns: XAML helps here too since it does only allow you to express objects and their relationships/properties, rather than logic. That forces you to separate logic from UI layout. The MVVM Pattern is very well suited for this task and allows for eay testability and interchangeable Views.
Added complexity in XAML can be also easily dismissed because the same code in C# gets easily more complex than the XAML markup.
I can't give you any insight into QTQuick though. Sorry
QtQuick is extensible via C++ plugins, actually what the Qt guys recomment is that you do the UI, Animations, Transitions etc in QtQuick/QML while all of your business logic is in C++/Qt. So this way you get the best of both worlds, you can debug your C++ code like you usually do, while at the same time making UIs becomes effortless and extremely easy.
Also another important think about QtQuick/XAML is that they are hardware accelerated, so for example you can get pretty good fps without any effort. So they are not slow at all for what they set out to accomplish.
It saves time, soo much time. I did a UI with code in 3 days, did the same in QML in 2 hours.
The point of declarative coding, i.e. WPF or QTQuick is to provide a separation between the developer and presumably the artist that is implementing the visual aspects of your application. With regards to WPF, I find that debugging gets to be a bit harder. As we speak, I am compiling the latest QT to look at QTQuick. (It takes a long time and I have time to look at stackoverflow :-) ) So, I don't have an opinion on that yet.
QML/XAML are:
Great for MVVM pattern
Hardware accelerated (QML with using OpenGL for Windows, MAC, Linux and Phone OSes... XAML with using DirectX for Windows and its phone version)
Closer to artists
You can create a GREAT and NICE UI using XAML/QML
Easier UI implementation
Nice animation is possible
In XAML, usually you can create a Silverlight version of your application just with a little changes
In XAML there is some great features such as Template, Trigger (DataTrigger, Trigger, EventTrigger), Binding (in any side and also both side together), Resource, Commands, DependencyProperty and Notifiable Properties.
But please note in XAML: (I am a XAML programmer, therefore i have not points for QML)
XAML debugging is not possible
For any change in XAML, all program must be recompile
Be more careful for performance. For example if you use much many RoutedCommands in XAML, your application will be unusable!
In XAML, some feature not works as expected. There is unfortunately some tricks. (It should be clear... should works as expected... isn't it? )
Be careful for some similar namespaces like BitmapEffect and Effect. There is different features and costs. (e.g. BitmapEffect has some effects with software render and Effect has some effect with hardware render)
In real world, artists could not use WPF as Flash (at least with good performance).
Some features works on special places. For example DataTrigger works just in Style tag not in Resource section.
There is some weaknesses in XAML. Some examples: there is not any sequential animation... you cannot do any calculation in XAML (you must write a converter in C# even for a liiiittle work! JavaSript is a great replacement in QML)... some attributes are duplicate. e.g. x:Name and Name... Controlling View from ViewModel is not clear. e.g. closing View from ViewModel (you need some CodeBehind)
Tooooooo much run-time errors. If you use some tags in bad place it will notice you for syntax error, but many of errors occurs just in the run-time. e.g. if i target Background property (instead of Background.Color) for ColorAnimation, it will compile successfully, but in running animation... BUMP... runtime error!!! in such case on Expression Blend, application will crash!!!

Good practice or bad practice

i am new to WPF and i have one question(the first one actually, more to come)
Is it better to add some logic, for example the bindings for the window, in xaml or in the code behind.
If you can put it in XAML, it's generally better to do that than be wiring up stuff in your codebehind.
For one thing, this lets you use tools like Expression Blend more effectively, since you have more stuff available at design time. It also further shifts view logic into the view itself, and helps you stay away from stuffing view-based code in your viewmodels or controllers.
Most people wouldn't consider a binding to be logic. Bindings should generally go in xaml. It is a good idea to put logic in a separate ViewModel class which you bind to.
It's kind of a religious debate right now. With an MVVM approach, you can essentially get away with the only code in your codebehind being the creation of your ViewModel and its assignment to your DataContext.
Even all of your event handling can be managed in your ViewModel using UI Commands.

wpf mvvm confusion

as per my understanding about mvvm is.
there is a model (entity class that also implement inotify...), view (xaml code) and some class as vm (kind of controller which normally inherit icommand) to let us make events/commands to be generated on specific event...
m just wondering about difference between viewmodel class and xaml's code behind class... why don't we simply consider and enhance code behind...
no considerable reason is in my mind to justify this...
or kindly write somethng with example to clear mvvm... and why mvc or mvp is hell for wpf app????
The Model does not implement INotifyPropertyChanged, the ViewModel does. The actual WPF view data-binds to the ViewModel. There is now a lot of documentation online for this.
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
MVVM is identical to Fowler's
Presentation Model, in that both
patterns feature an abstraction of a
View, which contains a View's state
and behavior.
http://blogs.msdn.com/johngossman/archive/2005/10/08/478683.aspx
In practice however, only a small
subset of application UI can be data
bound directly to the Model,
especially if the Model is a
pre-existing class or data schema over
which the application developer has no
control. The Model is very likely to
have a data types that cannot be
mapped directly to controls. The UI
may want to perform complex operations
that must be implemented in code which
doesn't make sense in our strict
definition of the View but are too
specific to be included in the Model
(or didn't come with the pre-existing
model). Finally we need a place to
put view state such as selection or
modes. The ViewModel is responsible
for these tasks. The term means
"Model of a View", and can be thought
of as abstraction of the view, but it
also provides a specialization of the
Model that the View can use for
data-binding. In this latter role the
ViewModel contains data-transformers
that convert Model types into View
types, and it contains Commands the
View can use to interact with the
Model.
MVVM is associated with WPF because WPF's data binding mechanism when combined with this pattern makes testable GUIs a breeze.
Check this two videos to get some idea. Both videos show developing application starting with everything in code behind and then they refactor to MVVM pattern.
Mike Taulty's series of videos (in fact there is 10 videos in total, check at least first and second)
Jason Dolinger on Model-View-ViewModel
Also, see this SO question for more links: MVVM: Tutorial from start to finish?
why don't we simply consider and enhance code behind...
(In addition to what other have already mentioned:) because it make your code easier to read. In the code behind file, you have UI stuff that is impossible or to complicated to do in XAML. In the view model code file, you have everything related to filling your form with data.
As with all design patterns, blindly following it is not the best idea. For very small windows, MVVM might not make sense. For larger windows, MVVM forces you to make a separation of concerns, which will usually make both your code behind file and your MVVM class easier to read, to understand and to debug.
First, for MVVM purposes you don't need the VM to inherit ICommand. Instead, VM contains a set of properties of type inherited from ICommand. So that View just binds to those properties. F.i.:
<Button Command="{Binding DoSomethingCommand}" />
And code-behind isn't used because it's basically inseparable part of the View. It's the same class your View is. You can't easily test it, and your code is often tightly coupled to the XAML.
And Model is not really obliged to (but can) support INotifyPropertyChanged. Whereas ViewModel should of course implement this interface to allow binding.
I suggest you to read a few introducing articles on the subject. It's not that confusing. This can be the first one: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
why don't we simply consider and enhance code behind...
Code behind is often (always?) the simplest approach...if you're a developer. But MVVM is designed to assist more than just a developer. MVVM is for the database girl and the graphics guy too.
Separating M (for the db) and V (for the artist) and VM (for you) allows each person to work independently of each other. So, for example, you don't have to wait for the graphics guy to make a UI before you can wire up the db. You can all work in parallel (in theory).
Separation of concerns means separate jobs.

Resources