Overusing code behind in my WPF application? - c#

I'm creating a simple WPF application for practice purposes only, but I have little experience in WPF. Using WPF XAML seems troublesome to me, as I have a lot more experience with C# Console and especially with the C#- and JS-driven videogame engine Unity, where devs have access to an Editor (analogous to the Design Window in WPF) and the code behind, with no XAML whatsoever. This is why I tend to use less XAML and much code behind.
For example here, I modify the Margin property of a button, while I set its Opacity to 1; this all happens upon a click event to the grid, which calls the function (exactly the way it's done in Unity):
public void Grid_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
RandomButton.Margin = new Thickness(0, 0, 0, 0);
RandomButton.Opacity = 1;
}
If I'm not mistaken, this can be achieved through Data Binding in XAML as well, although it seems to be a lot more complicated method seemingly producing the same result.
So my questions are: is there a difference between the two ways, say, performance-wise or in terms of expandability (which one would be easier to expand/modify later)? Which one is used in the industry?

There is no difference as far as the performance is concerned. For any element that you define in your XAML markup, an instance of a corresponding type will be created by the framework at runtime.
It is generally much easier to define the visual presentation of an application using XAML though. This is what XAML is used for after all: https://msdn.microsoft.com/en-us/library/cc295302.aspx
You still use a programming language such as C# to implement your application logic though, i.e. what happens when a mouse button is pressed etc. So setting/modifying the properties of any element that you originally create in the XAML markup using C# is fine.
Which one is used in the industry?
When it comes to enterprise WPF applications the recommended design pattern to use is MVVM (Model-View-ViewModel). You can refer to the following link for more information about it: https://msdn.microsoft.com/en-us/library/hh848246.aspx
The view is responsible for defining the structure, layout, and appearance of what the user sees on the screen and is typically created using only XAML whereas the view model and the model that are responsible for handling the view logic and business logic respectively is implemented using a programming language like C#.
You will find a lot more information and samples of how to implement the MVVM design pattern if you Google or Bing for it.

Hi being a WPF/XAML developer I would suggest you to use XAML as much as you can.Make use of commands and bindings i.e use MVVM architecture. What if you want to set the opacity using keys (example: ctrl+shift) you will have to write another code behind for that making your code redundant affecting performance of your app. Make use of MVVM pattern ( You can use MVVM light by galasoft). As of expanding or modification you will have to modify a single command method rather than modifying each event etc on the code behind. Easy to test ..Easy to build..Easy to modify..

Related

How to structure my project to use x:Bind

After beeing used to structure my project in WPF on a light MVVM pattern, I'm looking into WINUI for a new project.
In the elapsed time, UWP and x:Bind did appear and it looks like the pattern can be much lighter. The whole concept of ViewModel has changed (maybe in a better way).
I'm looking for a "correct and maintainable" way to use x:Bind, to display Properties and call a function from a class.
In my App.xaml, I'm declaring a Configuration which contains all the sub-instances. Let's say a Camera. This Camera has an IP, and a method to call from the UI. What is the minimum code to be able to call and display those ?
For the moment, I have created a CameraView which is a UserControl. I have declared a public Camera object inside, which I can call and display but I don't see the way to affect this from my Configuration. This "link" between the view and the model.
Thank you for the help.
Of course there is a simpler way to implement MVVM: Microsoft itself shows how in its own samples, on GitHub.
However, to summarize it all, have a look at my answer in this question: How to pass data between pages
There I show, step after step, how to easily implement a working pattern to have a “shell” that holds all the app’s data.
Best regards

How is MVVM in Xamarin.Forms/UWP/WPF any different from using code behind?

In learning Xamarin.Forms/UWP/WPF tutorials always tout MVVM as the design pattern of choice and I've followed suite, but I've never understood why. To contrast, in asp.net MVC the templated framework is used to great effect, Controllers deliver models to the view (HTML of some sort).
But in the Xamarin.Forms/UWP/WPF and others, we create a completely new class, ignore the code-behind file that cannot be removed and relegate it to telling our view where to look when binding data.
The only reason I could think of that makes MVVM better is if we could supply logic where different VM's could be 'injected' into the same view, maybe that would justify it.Though I have no idea how to do that.
Otherwise, how is creating a view model class better than using the code behind file? Is it really worse separation of concerns just because the view and code behind have the same name and are instantiated together?
MVVM pattern is much cleaner than using code-behind.
Separation of concerns
Imagine you have a view and a code-behind implemented. Now the business comes with a request to completely change the way the controls are presented - replacing them with new controls, changing layout and so on. Chances are, you will be forced to rewrite a lot of code just to satisfy the requirement, because the code-behind is directly tied to the view.
Now in case you have MVVM in place, you can easily swap the View part of the equation for any view which utilizes data binding to the right properties in a View model. You could easily present a single View model in several different ways - like creating multiple different views for different user roles while the view model stays exactly the same, you just choose what to display and how.
What view model actually creates is a middle layer between data and their presentation and makes it possible to more easily transform the data the view uses and change the presentation without affecting the view model if the interface is kept intact.
Data binding
Also if you are meaning purely code-behind without data-binding, the advantages of MVVM become even clearer. When you have a data-bound property that updates after user input in a TwoWay manner, for example if you have a form the user has to fill out, you don't have to remember to fetch the latest "changes" from the control using Text property, you know the latest version is already there in the data-bound property. In addition, you can add validation in the property setter, you can update other properties in the setter as well to orchestrate data handling in a much more abstract way than with code-behind approach, where you are tied to events and having to remember where the data come from and which specific controls and which specific properties you have to update. Imagine you display a given text in multiple places - with data binding you just set a single property and rely on {Binding} to display the text in all bound controls. With code-behind only, you need to remember which concrete controls display the text and when you add a new control, you have to update the code-behind appropriately, which is far less convenient.
Cross platform development
Another example would be having to develop a cross-platform application with native UI using MvvmCross. Here you can decide that some views or some functionality will not be available for certain OS or that you want to just implement it later. This is entirely possible - you just don't provide the UI for that functionality and the view model can stay the same.
View state
Finally - having all view state in code-behind means that when you navigate away, you must store the state somehow and restore it when navigating back because a new page is created. With MVVM you may decide to keep the view models of the navigation stack in memory and when navigating back just set the DataContext of the page to the existing view model instance to get back just in the same state as you left off.
Overall I see MVVM as a great pattern to improve flexibility of your codebase and it makes your solution more future-proof and resilient to changes.

How to integrate Windows.UI.Composition animations into UWP MVVM Light app

I’m utilizing the Windows.UI.Composition framework for the first time in my app. My app is built on MVVM Light. I'm updating the app to add more transition animations between elements.
The prevailing wisdom with MVVM is that you should keep your UI code in XAML as much as possible, binding visual states to the ViewModel properties, etc. But all of the Windows.UI.Composition material and samples I’ve been seeing, define the UI manipulations in the code-behind instead.
Let’s use a show/hide scenario as an example. I have a bool property in my ViewModel like ShowTheBox. I bind TheBox’s Visibility property to the ViewModel property. The Box will show or hide automatically based on changes in my ViewModel.
Now, using Windows.UI.Composition, I want to add fade-in/fadeout animations to the visibility changes of TheBox. Where is the best place to put that C# code and how do I bind that transition to my ShowTheBox property?
I wouldn't agree that point of MVVM is to keep UI code in XAML exclusively. The point of MVVM, as any other layer separation pattern, is to separate UI layer from app's logic. MVVM just adds its own flavors in form of bindings.
So I think that when you have complex animations and other UI related stuff, it's perfectly fine to put them in code-behind. But before doing that, you might want to try to extract as much of your animations as you can to custom controls which will facilitate your doubts a little.
EDIT:
Making a lot of your UI logic bound directly to ViewModel properties isn't always a good solution. Layer separation exists for a reason, so when you compose your layers, imaging that you're writing a Xamarin app and have common ViewModels, but different Views for different platforms. Now you're not even sure if on another platform is gonna have those animations or not. Maybe a flow that takes one screen on UWP will take two screens on iOS, or something else. To have a property "IsVisible" which serves only for one of many views isn't making much sense now, does it? So you have to find some common denomination for ViewModel and move everything else to UI layers.
At the end of the day, MVVM is just a pattern which helps you write a better code. It's understandable to want to stick to all the good practices as much as possible, but if it doesn't make sense for your app - is it worth it?

Using Partial Classes in WPF

I have done quite a bit of research in the last few months and haven't been able to really find a good answer for my question yet:
A little background info: I am new to WPF and was asked to create a project using it. I learned most of the concepts on my own, but am struggling with one major issue. There is just too much code in the MainWindow class.
The reason there is too much code: There is too much code because all of the events for my UI Elements must be controlled in this one class.
Now I just recently discovered the use of partial classes. So I plan to split the events off into a seperate file. I am just wondering if there is any better way to decrease the size of my MainWindow class? I haven't been able to find a way to pass controls between classes, because I know it is not good to pass TextBoxes, or ListBoxes etc. between classes or methods. (I do understand, however, that you can pass parameters such as textBox1.Text or similar properties, but that doesn't fix my issue.
Introducing partial classes will not make your code any better, it will just spread the bad code over different files.
The "standard" way of developing WPF applications is to use the Model-View-ViewModel (MVVM) pattern. Using this enables you to have XAML-only views, view models that control their behavior and models that provide your application data.
There are tons of tutorials on this on the web. MSDN has a good introduction to this pattern. Having read this you should have a good overview of MVVM and can start applying it to your application.

WPF C# MVC/MVP pattern and user control code-behind

I am developing a large-ish application in WPF/WCF/NHibernate/etc. and have implemented the MVP pattern (although this question is still relevant to MVC) as the core architecture.
It feels quite natural to extend and add functionality as well as to come back and make changes on certain bits and pieces, as far as the core architecture is concerned (controllers, views, etc).
But at times the code-behind-ness of custom user controls that I create feels as if it "breaks" the MVC/MVP paradigm implemented, in that code concerns leak in the design and design concerns leak in the code. Let me clarify again, this is only for user controls. It is my personal opinion that this code-behind model (for both ASP.NET and WPF) is a 'Bad Thing', but no matter what my opinion, I'm stuck with it.
What are your recommendations for best practices in such a scenario? How do you handle such concerns? Do you for instance work around the code-behind-ness of custom controls and if so how??
Since you are using WPF, you should really look into the MVVM (Model-View-ViewModel) pattern. It is a form of the Presentation Model (PM) pattern discussed by Martin Fowler. WPF is very binding-oriented, and provides a very powerful and rich data binding framework for XAML. Using MVVM, you can completely and entirely decouple your ViewModels from your Views, allowing truly POCO UI development that offers the ultimate in separation of concerns and unit testability.
With MVVM, you will be able to modularize and decouple all of your views, including Windows, UserControls, etc., from the code that drives them. You should have no logic in Code Behind other than what is automatically generated for you. Some things are a little tricky at first, but the following links should get you started. The key things to learn are the MVVM pattern itself, Data Binding, Routed Events and Commands, and Attached Behaviors:
MVVM
Data Binding
Attached Behaviors
Attached Commands (VERY USEFUL!)
Routed Commands
Routed Events
WPF + MVVM has a bit of a learning curve up front, but once you get over the initial hurdle, you will never, ever want to look back. The composability, lose coupling, data binding, and raw power of WPF and MVVM are astonishing. You'll have more freedom with your UI than you ever had before, and you will rarely, if ever, have to actually bother with code behind.
I happen to like code-behinds (yet another personal opinion), but they work only as long as they do nothing but facilitate interactions between control events and the rest of the application. I'll admit that I've seen a lot of counter-examples, though. I even wrote a few of them....
Really, all the code-behind should do is "oh, someone clicked this button; there's probably something that wants to know about that." PRISM (from MS patterns and practices) provides a lot of architectural infrastructure for WPF and Silverlight; that includes a publish/subscribe interface that allows the controls and the code-behinds to simply publish an event while not even being aware of possible subscribers, or what the subscribers might do with the event. PRISM also adds commands for Silverlight.
A common variant of MVC for WPF and Silverlight is MVVM (Model, View, ViewModel). The ViewModel makes data available to the user controls in some form that is most useful (such as ObservableCollections, to facilitate two-way binding).
Custom Controls are there to display stuff. In that regard they are no different than a button or a drop down combo box. The trick is that don't let them handle stuff directly. They need to send stuff through the View Interface and the Presenter need to likewise interact with them through the view interface.
Think of it this way. If you ignored MVP the custom control would interact with the model in specific ways. what you doing with MVP is taking those way and defining them with the View Interface. Yes you are adding an extra call layer but the advantage is that you thoroughly document how it interacting with the rest of the system. Plus you get the advantage of being able to rip it out and replace with something entirely different. Because all the new thing needs to do is the implement it's portion of the view interface.
If you have a specific example I can illustrate better.

Categories