1

I've read plenty of articles around different patterns in use with WPF and this is something I've yet to understand: should a code-behind file be considered part of the view? As a consequence, should code-behind files be allowed utilise knowledge of specific elements in the markup?

I have a number of scenarios where the controls which are present in a view are influenced by data in the view model (eg a button for each list item). Currently, I handle these kinds of scenarios in the relevant code-behind file. To me, this feels like an implementation detail of the view and thus part of it; another view of the same view model might choose a list box of list items for example).

2 Answers 2

7

The XAML and the code behind together represent the view, i.e. the visual representation of the ViewModel. A lot of the time the tools and methods available in XAML (i.e. data-binding declarations with formatters and whatever templates you need) are sufficient to control the layout to your satisfaction, and so the code behind is not needed or can be empty.

However, I've come across situations before where presenting the data how I want using just XAML and no code is a real hastle. In these situations, if it's more natural to generate the UI controls in the code behind, then do it. It's essentially only a different way of defining your view (i.e. in procedural code rather than declarative XAML).

I have a number of scenarios where the controls which are present in a view are influenced by data in the view model (eg a button for each list item). Currently, I handle these kinds of scenarios in the relevant code-behind file.

If I understand the situation correctly, then I think in WPF this can and should be done with DataTemplates and DataBinding in XAML, so there's no need to use the code behind file.

0

It IS part of the view! Ever noticed your xaml.cs is a partial class? So yes, your code behind know and can use specific elements of the view.

Personnally I do my best to stay away from this and use MVVM, but it all depends on what application you are buiding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.