Good practice or bad practice - wpf

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.

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's with empty code-behinds?

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.

Silverlight communication/commands/events? between view and viewmodel?

I am just getting into the Silverlight world, and wish I didn't learn WPF first so I wouldn't be so frustrated with the little things that are missing.
In WPF I was using commands (RoutedUICommand) for my view/UI to handle "events" (by event I mean something the user did) and passing them to the viewmodel.
Now in silverlight I find that I can't do it that way and on top of that there doesn't seem to be a consensus. I dislike putting code in my codebehind for my views but I keep finding myself having to do so, unless I am willing to subclass damn near every usercontrol I use. Or write a million lines of xaml for a one line codebehind statement.
And even then, I don't konw If I should use events, commands, or what seems like the best fit for me the LocalMessageSender/LocalMessageReceiver.
bottom line, is there a generally accepted approach for what must be a very common situation: telling the viewmodel what the user did?
Oh im using SL 4 if that matters.
is there a generally accepted approach for what must be a very common situation: telling the viewmodel what the user did?
Yes its called binding.
When it comes to button clicks in Silverlight 4 you should be looking at exposing a property on your ViewModel that has the type ICommand, you can then use a standard Binding on things like Button Command property.

Where should I set the DataContext - code behind or xaml?

(honestly I searched and read all the 'related questions' that seemed relevant - i do hope i didn't "miss" this question from elsewhere but here goes...)
There are two different ways (at least) to set the DataContext. One can use XAML or one can use the code behind.
What is the 'best practice' and why?
I tend to favor setting it in XAML because it allows a designer to define collections on their own but I need 'ammunition' on why it's a best practice or why I'm crazy and the code behind is the bomb...
A third way you might look at is using a locator service. I usually have one class that is responsible for the creation of all my DataContext(VM's in most cases for me) and I create an instance of that class in the App.xaml Resources. Then I bind the DataContext in the XAML of each individual page.
i.e.
<Page DataContext="{Binding ViewModel,Source={StaticResource Locator}}" >
I think it depends on what you are setting the DataContext to, and ultimately personal preference.
I personally always do it in the code behind of my views because I find it overall cleaner, and it was how I was taught MVVM. Another thing to keep in mind is, there are times you may need to change your datacontext depending on what you are working with. If this is the case it's much cleaner/easier to do in the code behind rather than in XAML.
As you can see by the answers so far opinion is divided. In truth there is no best practice (I do get bee in my bonet about discusions of "best practice" in the Silverlight world, its way too young for best practice to be truely known.)
The reality actually is that you can't set the "data context" in Xaml. Unless you actually construct an object instance like this:-
<UserControl>
<UserControl.DataContext>
<local:MyDataProviderThing />
Ultimately something external has to assign either the DataContext property directly or indirectly via another property or via binding (as in Stephan's answer). Its this external context which is dictates whether it makes sense to do it in Xaml or not. Many MVVM solutions use a binding in Xaml, in some cases simply to avoid there having to be any code at all in code-behind rather than it truely being "better". Others set up the DataContext in code using a base class that your control derives from.
DataContext of the user control/view I assume? One advantage of setting data context in the code behind is the availability of dependency injection. Your DI container can take care of any dependencies for you dynamically at run-time.
With this pattern, I frequently set a view's Blend design DataContext in xaml using d:DataContext. The "design version" can provide mock data for use in Blend, while the true implementation is resolved at run-time.

Can a ViewModel talk to View in MVVM pattern?

In MVP pattern, a Presenter has an interface of View so the presenter can call iview.DoSomething().. What about in MVVM pattern?
According to John Gossman's UML diagram http://blogs.msdn.com/johngossman/archive/2006/04/13/576163.aspx , ViewModel doesn't have an interface of View. So, seems like the ViewModel and View should be communicated via Binding only. (or use attached property or blend behavior or etc).
What do you guys think?
I agree with John Gossman. The way the ViewModel "talks" to the View is through Bindings only. In fact - the ViewModel shouldn't care about the View at all. It should simply make data available through properties, and it's up to the View to decide what it will dynamically bind to in the ViewModels. If the ViewModel wants to tell the View something this should occur implicit through Bindings.
A similar question was asked an hour ago - here.
The whole purpose of MVVM is to vastly reduce the amount of code in your code-behind class of your WPF form or user control. The idea is that anything that would be handled by the view in classic MVC/MVP can be translated over to the VM by using a combination of data binding and/or commands. In my general usage of MVVM I have managed to completely remove all of the code-behind in my forms/user controls and the VM has no direct knowledge of the view it is controlling. If you have a situation that really cant be handled by data binding or a command then please elaborate on your initial question and I (or one of the many, many more talented MVVM'ers on here) will try to point you in the right direction.
It typically does - through events on INotifyProperty changed, if nothing else.
Can a ViewModel talk to View in MVVM pattern?
Yes, but in a decoupled way. It’s allowed to introduce an interface IView for the communication.
The MVVM pattern is about to move the logic from the View into the ViewModel. This way we are able to unit test this logic.

Resources