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?
Related
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.
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..
I’ve an Interface with many textEdit fields. But any Fields have dependencies to others.
For example:
When textfield_1 is filled, textvield_3 and 4 disabled. But my Layout is Dynamic and I don’t want to Code this dependencies Hard.
Does anyone have an Idea or Solution to Save or hold this dependencies in my Application? And how can I check it.
If I understood your intent correctly I would say the basics would come from ViewModel (as in MVVM design pattern). You could go with the simple INotifyPropertyChanged route or something more "reactive" like RxUI: http://www.reactiveui.net/
All changes happen in the ViewModel (so you can also share it across platforms) and the UI just reacts to changes in the ViewModel data.
I'm trying to learn MVVM and WPF and I'm using the MVVM Light Toolkit. Here's what I'm not fully understanding and maybe it's due to an incorrect architecture of my UI.
What I'm trying to accomplish is pretty simple actually. This is a utility application by the way. I want a window that serves as the 'controller' so-to-say that has a set of buttons. Each button should change the content of a frame. Example: one button loads a 'screen' ( or a 'view' if you will ) that allows the user to configure an 'Agency' which is a custom object. Another button loads a list of Users from the Agency that was in the first 'screen'. This 'Users' view needs to also be loaded in the same frame. In fact, as of right now, the window with all the buttons really is only responsible for loading the 'screens' in the frame. The meat of the application will be within all the separate 'screens'
What I am not understanding is 1) how to let each screen/view know about each other since one is dependent upon the other. It seems that in MVVM the ViewModel shouldn't know about anything. But in my case, I need to pass information around ( such as my Agency ).
If I can get some hints on what I need to look into, that would be great.
Thanks!
Some ideas that might connect some of the dots:
You'll most likely have one viewmodel per view ("screen").
Each viewmodel will contain all of the logic for its corresponding view
Viewmodels can and will know about the models (Agency, Users)
Viewmodels can communicate with each other via the Messenger in MVVM Light
Think of MVVM Light's Messenger as an "application-wide eventing system". When you send a message out from one view model, any other view model can be listening for that message/event and react to it as needed.
Does that help at all? Keep your thoughts coming and I'll keep commenting and I'm sure the community will as well :)
Few things:
each of your screens, should be separate view (eg. user control or new window - I suppose you've done that already)
every part of model (eg. Agency, User) you want to display in your application, should be wrapped with its dedicated view model
your views don't really need to know about each other; you can use commands or events on view models to get rid of those dependencies
view model only needs to know about one thing: model it's building on
it's good to think about view as really simple class, with one single responsibility of rendering content; no logic, no code behind (unless it's purely UI/display related) is something to follow
You can try to prepare your models first (if you haven't done that already), then make view models for them (thinking what properties of models you want to expose to views) and once that's ready, build your views basing on view models. Other way around is also viable option - pick whichever feels more natural to you.
One more thing: since you mentioned you can display several screens in one (I assume) main area, think about equipping your view models with something along the lines of bool IsCurrentlyActive property. This way, you can easily show/hide views with button clicks and still utilize binding mechanism.
They shouldn't know about each other. That is what the Messenger is for controllers and views subscribe to the events they are interested in. That way they don't need to know or care where they event originated.
Hmm Kendrick is faster. What he said.
Also it sounds like you kind of want an Outlook type interface, some navigation that loads other views. I had the same question a while ago. How to do Regions in WPF without Prism?
To better understand the MVVM pattern look at this article: WPF Apps With The Model-View-ViewModel Design Pattern
Also I advice you to look at Caliburn Micro framework.
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.