Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 372
dovholuk Avatar asked May 11 '10 14:05

dovholuk


2 Answers

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}}" >
like image 105
Stephan Avatar answered Sep 23 '22 00:09

Stephan


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.

like image 25
jsmith Avatar answered Sep 22 '22 00:09

jsmith