I'm trying to decide where to draw the line on the use of F# and C# in enterprise software development. F# for mathematical code is a no-brainer. I like F# for GUI work even though it lacks GUI designer support but, of course, there is more resource availability of C# GUI people in industry. However, I am not too familiar with C#+XAML GUI development so I'm concerned about introducing bias.
In the case of one client, they have dozens of similar GUIs that are quite static (changed yearly) and a few other GUIs that are very dynamic (e.g. business rules engines). They already have F# code live and are already investing in F# training so skills availability isn't an issue. My impression is that C#+XAML let you build static GUIs (a few sliders, a few text boxes etc.) easily but I cannot see how the GUI designer would help with programmatic GUIs like a business rules engine. Am I right in thinking that maintaining a battery of mostly-static GUIs (e.g. adding a new field to 100 separate GUIs) will require manual labor? Also, am I right in thinking that the GUI designer is of little use in the context of heavily programmatic GUIs so something like a business rules engine would be written primarily in C#+XAML with little use of the GUI designer?
I've done a good amount of GUI and non-GUI programming in C# and F#, in work and play, heavy programmatic and static... and I believe your stated impression is accurate and practical. (note that I am more familiar with WinForms than with WPF, but I don't think the differences matter here).
My impression is that C#+XAML let you build static GUIs (a few
sliders, a few text boxes etc.) easily but I cannot see how the GUI
designer would help with programmatic GUIs like a business rules
engine.
This is absolutely my experience. For mostly static GUIs, I prefer using the WinForms designer with C#. The tooling combo is great for these scenarios and is more productive than hand-coding the GUI with F# and no designer (now, if there were F# support with the designer, I would have no hesitation preferring that). I'm Only Resting is an example where I have preferred C# with the WinForms designer over pure F#.
And for heavy programmatic GUIs, I believe it is best to avoid the designer altogether, rather than to attempt to go half designer half programmatic (it gets real messy, real quick). So in these cases I definitely prefer hand-coding the GUIs in F#, since everyone knows F# is the more expressive language ;) FsEye is an example where I have preferred pure F# over C# with the WinForms designer.
Am I right in thinking that maintaining a battery of mostly-static
GUIs (e.g. adding a new field to 100 separate GUIs) will require
manual labor?
Probably. I don't believe there is really any ready solution for this problem since it is really quite a large one. But there might be some best practices out there for building a custom solution right for your suite of software.
Also, am I right in thinking that the GUI designer is of little use in
the context of heavily programmatic GUIs so something like a business
rules engine would be written primarily in C#+XAML with little use of
the GUI designer?
Yes, like I said early, it is my belief that you ought not try to mix the GUI designer with heavy programmatic GUI programming.
I recently built a directed graph visualization application using purely F# and WPF.
For the 'programmatic' GUI parts, I essentially built WPF custom controls that I could operate with data binding and MVVM.
For the static parts I used XAML with out-of-the-box and custom WPF controls.
I used the FSharpX WPF Type Provider extensively for MVVM binding.
And this 'book' helped me quite a bit to get started. http://wpffsharp.codeplex.com/
Some things don't come naturally with F# and WPF but in almost all cases a reasonably elegant solution was found. Some WPF data binding strings did become large and unwieldy.
I don't know how exactly to answer the question as it's somewhat hard to get hold to so I just give you my 0.05$:
If you do WPF with a good MVVM (there are even Rx-Versions that are influenced by FP-land) you won't write code-behind (or almost none) - and with WPF type-providers and all the other great stuff that's around you can already write WPF-F# applications without any problem (even designer support is no problem - just use BLEND if you can - if not you can still seperate the GUI into a dumb C#-lib.)
so why don't I write most GUIs in 100% F# then?
Well to be honest... it's the lack of refactoring and tools like ReSharper - it's just frustrating that I cannot search for F#-symbols or types because there is no freaking support in VS/R#er right now.
It's strange but writting MVVM code where you have to create much trivial code for your Viewmodels seems to be easier to do in C# with the right tools right now (for example: I can configure R#er to insert me all the code for public probertys with private/public setters and INotifyPropertyChanged based on internal fields by just hitting - and choosing the right option - this will generate lot's of very dumb code but it's much faster that you could do in F#)
As you have pointed out, F# is a much scarcer skill among programmers in the general IT industry, whereas every man and his dog knows C# (or for that matter Java, C/C++ which easily translate across).
Thus from a purely managerial point of view it likely makes more sense to go with C#+XAML over F# because of a number of factors:
Programmer's salaries - hiring an F# guru adds quite a bit to the salary budget
Development time - this could be argued either way see 1 for a good comparison
Corporate risk - usage of F# greatly increases the risk factor in each of the categories:
Programmer leaves company and takes intellectual property with them
Programmer leaves company and company cannot hire a replacement => project misses deadline
Company does not have adequate metrics available to gauge the time required for the project
Language becomes depracated and code has to be ported (not as great a concern but still higher-risk than C#)
Etc. etc.
However, from an engineering perspective, F# (perhaps with an add-on library for visualisations) is able to simply generate a powerful GUI. C#, though, also has this capability - you can generate your entire GUI without using XAML programmatically.
As for adding a new item to 100+ GUIs, here I don't see how XAML is a disadvantage at all. If I understand your question correctly, you can use a Data Template which you can update once in XAML and have the change propagate across all your GUIs.
In conclusion I would suggest to you that unless you have a strong reason to use F#, stick with C# as it will reduce risk to your company in the long term.
I see alot of confusing answers and solutions here. F# and C# can be combined in solution. Let C# manage GUI and F# manage packages. Also, XAML vs WinForms is a no brainer. With XAML, There is more than enough room for code behind to do any and everything you need. If you're using WinForms then I do believe you need to retire from it immediately. WPF for example, is far more flexible and extremely powerful with GUI options far above those of WinForms. Not to mention the binding power of XAML. XAML is static but communicates with code behind just well and can communicate to any and all .NET languages. Use F#, use C# together and definitely leave the world of WinForms forever. Here is a little project that I've done. It uses only a combinatin of WPF, Silverlight, WCF, F#, C#, and VB.NET. WinForms wasn't touched and if you look closely you'll see that acheiving this with WinForms would have taken ages. I could have completed this with only one language but swapping helped save time depending on the situation but I only went forward, never backwards. WinForms as well as all other legacy options were ignored and never used.
Related
Keeping in mind what CannibalSmith once said - "All the answers are saying "WPF is different". That's a huge understatement. You not only have to learn lots of new stuff - you must forget everything you've learned from Forms. It's a completely new way of doing UI."
.. and having many years of experience with visual Windows desktop applications development (VB6, Borland C++ Builder VCL, WinForms) (which is hard to forget), how do I quickly move to developing to say well-formed WPF applications with Visual Studio?
I don't need boozy-woozy graphics to give my app look and feel of a Hollywood blockbuster or a million dollar pyjamas. I always loved tidiness of standard Windows common controls and UI design guidelines, end even more I enjoyed them under Vista Glass Aero Graphite sauce.
I am perfectly satisfied with WinForms but I want to my applications to be built of the most efficient and up-to-date standard technologies and architectured according to the most efficient and flexible patterns of today and tomorrow, leveraging interface-based integration and functionality reuse and to take all advantages of modern hardware and APIs to maximize performance, usability, reliability, maintainability, extensibility, etc.
I very much like the idea of separating view, logic and data, letting a view to take all advantages of the platform (may it run as a web browser applet on a thin client or as a desktop application on a PC with a latest GPU), letting logic be reused, parallelized and seamlessly evolve, storing data in a well structured format in a right place.
But... while moving from VB6 to Borland C++ Builder was very easy (no books/tutorials needed to turn it on and start working) (assuming I already knew C++), moving from BCB to WinForms was the same seamless, it does not seem any obvious to me how to do with WPF.
So how do I best convert myself from a WinForms developer into a right-way thinking and doing WPF developer?
Read this questions:
How to begin WPF development?
Is there a WPF Cheat Sheet outhere?
Learning MVVM for WPF
Learning WPF and MVVM - best approach for learning from scratch
MVVM: Tutorial from start to finish?
Download and work through this Microsoft tutorial: Southridge Hands-on-Lab
Check this videos:
Mike Taulty's series of videos
Jason Dolinger on Model-View-ViewModel
And after that, take a look at StackOverflow questions tagged with both wpf and mvvm
Keep in mind that MVVM seems suited only to single window applications.
I dived into WPF based on inexperience and general recommendations that it would suite better a kiosk project, especially one where the customer has given me photoshop images of all the application screens. Having cool graphics was a requirement for this project and I liked the vague resemblance of WPF with web development.
I found out a few downsides
1) there is no such thing as an official MVVM toolkit. There are a lot of them, all backed by an individual. A shot at a toolkit by Microsoft has been put on the back burner one year ago and there is no VS2010 support.
2) programming a multi windows application, sort of a simple wizard with back and forward, is plain nightmare. I got out of this with a clean design defining a delegate for each UI action and a command for each business action, but still I think it is too much involvement with a framework to be justified, and you cannot show the result of your tests to this customer expecting excitement.
3) You give up the habit of double clicking a button and adding some code. This leaves a nagging feeling of using the IDE against its nature. Basically you use Visual Studio as a text editor and an interface designer, still with a great help from the tool.
The upsides, so far are:
1) defining visual components is very flexible, fast and easy and you can choose between VS and Expression Blend. Animations are simple to create.
2) data binding simplifies the application. You define a DataContext and bindings and do not have to move data from the business logic to the interface yourself, as long as you have a property for everything that must be displayed.
3) You can reduce the amount of business logic in the interface to zero. It is easy to separate the application behaviour from its looks, so you can skin your interface in ten different ways with little effort and test all of your logic without opening a window.
4) you leave a door open to going with Silverlight if they ask you.
My conclusion is that if you have an MDI application in mind you might find yourself in big trouble. You should be aware that, if you choose WPF, you are ploughing ground for future generations rather than getting on a train that will get you there fast and easy. There is no established way to do things, especially those that are not covered by demos.
Toolkits, all things considered, are not so important and each of them will serve you well. In fact a couple supporting classes are enough to start and there are no fancy wizards, it is up to you to follow conventions.
You might even make your own if a few hours, once you understand what is involved in the logic. The downside is that you will have to really understand it well to bend the application your own way.
As I said above, I had to learn a lot just to show a new view when they click a button keeping the code clean. Take the time to see the videos cited elsewere on StackOverflow it will save you time.
if you are looking for books just look at this previous post
What WPF books would you recommend?
Having got into WPF this year, the most important thing for me was learning how to use the Model View View-Model pattern for separating the view from the app logic. As a general rule of thumb if you find you are placing a lot of code in the code behind for your view then you are "doing it wrong".
I found that coming from a WinForms background I was putting in lots of event handlers and doing stuff in my code behind. As I became familiar with MVVM and WPF features I found I was able to remove the bulk of my code behind and replace it with views binding to view-models.
It was articles like this one from Josh Smith that helped get me started on the MVVM path:
http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx
Once you have started to get the hang of displaying data view MVVM bindings, have a look at commands and specifically the ICommand interface. They are the main mechanism by which actions from the user triggers operations to execute. So rather than having a OnClick handler for buttons, you bind the Command property of the button in XAML to a property in your view-model that exposes an ICommand implementation.
My 2c - Donovan
Try this smashing hit.
Windows Presentation Foundation - Unleashed By Adam Nathan
(source: adamnathan.net)
I've seen a lot of questions about the merits of WPF here, and essentially every answer says it's the bee's knees, but essentially every answer also talks about things like XAML, in many cases graphic designers and Expression Blend etc. My question is, is it worth getting into WPF if you're a solo coder working in C# only?
Specifically, I don't have a graphic designer, nor any great talent in that area myself; I don't use point-and-click tools; I write everything in C#, not XML.
Winforms works fine in those conditions. Is the same true of WPF, or does it turn out that important functions can only be done in XAML, the default settings aren't intended for actual use and you have to have a graphic designer on the team to make things look good, etc., and somebody in my position would be better off to stick to Winforms?
I'm a code person myself, and to be honest, it doesn't matter. Even if you don't know anything about graphic design, you can still use the editor in visual studio to design an UI. The designer features an drag&drop designer as Win Forms does, so that doesn't really pose a problem. Even though I'm a code person, I have no problem with xaml, as it is, in some way, code again. I had problems with the xaml at first as well, but I got used to it, and stuff I had to do in code in Win Forms was quite easy in xaml.
Databinding simply rocks, you don't have to care about getting the data to the UI, you simply have an ObservableCollection<T> or similar, and one Property in the xaml code and everything gets done for you. Want to format the data? Simply add a formatting property to the binding. Want to color the text according to the value? Template Selector class with 15 lines of code, Binding and Template selection in the xaml code of about 10 lines. I'm really growing to love it, and with time (as with any other new technology) you get used to it, and produce good looking stuff.
Short answer: is yes, you can do WPF with code only.
Longer answer: The part about a designer being able to work on the UI and a developer on functionality is really just a side-effect of decoupling functionality from presentation.
What WPF brings to the table in a powerful way is data-binding which enables you to use wider range of design patterns. MVVM has been discussed quite a bit recently.
The various MVVM framework encourage convention over configuration allowing you to write less code to accomplish the same goals.
This decoupling also has the nice side effect of making your application more testable (you don't have to write tests if you don't want to, but at least the option is there).
Moving to WPF from WinForms will most likely be worth it for you for new development. You could in theory keep doing what you've been doing with WinForms (just with new libraries), but it gives you the option to incorporate newer tools into your development as you become more comfortable with technology.
If you haven't seen it already, the BabySmash series by Scott Hanselman is pretty interesting.
IMHO, it is worth going the WPF route if only to ensure that you build these skills. I have toyed with Silverlight which is XAML based and I could transfer much of that knowledge to WPF even though SL is a subset.
And to be honest once you get used to it, most UIs are build just as easily with WPF as with WinForms. And the tooling is quite nice, using SketchFlow for prototyping is useful, and does not require you to have any real artistic skills other than what you have for doing WinForms stuff. I believe going forward, it would only benefit me to be learning more about WPF, and I believe that would be the case for others.
Everything that can be done in XAML can also be done in code due to the fact that XAML is merely a DSL for instantiating and configuring graphs of objects - specifically those in the WPF library (System.Windows). If you're building line of business apps, then there's very little that WPF offers that isn't available at all in WinForms. The key difference is that WPF allows you to do many things much more easily and flexibly, due to its more advanced object model.
I think that WPF is certainly worth learning, but if you want to do it without learning XAML, then I think you'll probably find it more difficult grok.
It's also worth considering that many WPF developers write the XAML by hand (whereas their designer counterparts will be more likely to use Blend in the first instance) partly through necessity (the WPF designer prior to Visual Studio 2010 wasn't very good) and partly because the object model lends itself to a more concise expression in XAML than in C#. XAML is itself quite a small language but the object model it is used to define (the WPF object model) is huge - and that's where the complexity comes from.
If you have no compelling reason to stop using WinForms, then don't. However, if you can push aside your preconceptions about writing code in XML rather than C#, then I think you might be surprised how this different approach to building a UI might clean up your code.
I say WPF can be for you, and if you don't want to go the xaml way and do code only you should go ahead and do that, in xaml certain thing are impossible but it is the preferred way of doing layout, but no one forces you not to do it in code, however if you learn xaml you will produce UI elements faster, then you would in code, so that's something to remember.
this is an old post but...
To my opinion, there are no bounderies when you code by your self in any environment and that always something needs to be discovered. People have created layouts in code for many years in the past, but certain factors moved the community to create graphic and ui tools. But again, nothing lasts for ever and trends change quickly. Also remember the transition from ASP inline coding to layout composition style of ASP.NET and then back to inline with ASP.NET MVC. Was it a step back? Certainly not, because it was supported with other techniques and tools like razor, dynamic language, model binders and more.
So, actually noone can tell you the right way to work as long as you follow basic rules and standards and realise that it's not just code but rather today's code, with all the lambdas, linqs, expressions, anonymous, DLRs etc.
Who knows? Maybe you will be the one to create a new way of expressing and driving content.
We're in the early design/prep phases of transferring/updating a rather large "legacy" 3 tier client-server app to a new version. We’re looking at doing WPF over Winforms as it appears to be the direction Microsoft is pushing development of the future and we’d like the maximize the life cycle/span of the apps. That said during the rewrite we’d like to make as many changes to our data access/presentation model to improve performance as much as possible up front as many.
I’ve been doing some research along that vein but the vast majority of the resources I've found that discuss WPF focus only simple data tracking apps or focus on the very basics UI design/controls. The few items that even discuss data presentation are fairly elementary in depth.
Are there any books/articles/recommended reading/other resources recommended for development related to large enterprise level business apps?
Any “gotchas” that should/could be avoided?
General advice to minimize the time underwater
I've been developing a large enterprise-wide WPF application for almost 2 years. As with any UI development, it's important to understand the best UI design pattern for the particular technology you are using. From my experience with WPF, the Model-View-ViewModel design pattern is the most prevalent. Once you understand the data binding powers of WPF, it is easy to see why a pattern like the M-V-VM is so accepted. Even if you don't follow the M-V-VM pattern (or a variation of it) word for word, understand the big picture solution that the pattern addresses. Basically, keep your UI/XAML file (View) in a separate file and all the code-behind/logic (ViewModel) in another file. The View simply reacts to changes in the ViewModel.
Keeping the ViewModel separate, you'll have several benefits.
Easy to create automated tests for the ViewModel object because there are no graphic components in it. It's just an object with methods/properties.
Easier to split the work up between developers (e.g. one developer builds the View while another developer is building the ViewModel).
It's much easier to use multi-threading in the ViewModel since it never interacts directly with UI controls. You know what I mean if you ever tried updating a textbox on a background thread.
Below are some of the pros/cons of WPF vs Window Forms from my experience:
Pros:
Much better UI appearance and experience to end users. WPF allows you to have ultimate control of the appearance of any UI element. (e.g. a list box that contains a picture/button/text for each row).
Data binding is amazing. Binding your UI controls in the XAML file to point to specific properties on your ViewModel class, and everything just works. The UI simply responds to any property changes of the ViewModel. Complete separation! You'll really see the benefit of this if you ever want multiple windows/user controls to display the same information simultaneously and automatically keep in-sync.
Everything I've read on MSDN is that Microsoft is putting much more resources into WPF than into the old Window Forms.
Cons:
Big learning curve. Don't be surprised if it takes a couple months before developers with no prior experience with WPF make a somewhat sophisticated UI. It's a brand new technology and there will be a learning curve.
Some common user controls weren't developed by Microsoft yet (e.g. masked textbox, data grid). However, Visual Studio 2010 does come with a data grid and it works well. Also, there are plenty of 3rd party controls on the market.
The best resouces I can think of:
"Pro WPF in C# 2008" - This book is awesome. It's over 1000 pages. It covers almost ever area of WPF. Use it like a reference book. It's straight to the point with easy to understand examples.
Link to Josh Smith's article on the Model-View-ViewModel pattern: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090016
Like I mentioned earlier, don't get too hung up on someone's version of the M-V-VM pattern. More imporantly, understand how WPF allows you to easily create a ModelView and have the View automatically respond to changes.
Good Luck! You won't regret WPF if you can get past that darn learning curve.
The VS2010 team has kept a blog about obtaining good performance as they switched to WPF.
They have a series, WPF in Visual Studio that offers a few suggestions (especially the second part).
General advice to minimize the time underwater:
Learn data binding as soon as you possibly can. Use data binding in every single prototype you make. Even if all you're doing is playing around with how panel layouts or grid splitters work: put an XmlDataProvider in your window, create XML test data, and bind to it. This is especially useful if you're using Kaxaml to prototype. I don't know how important that's going to be once VS 2010 is in your hands, but if you're using VS 2008 Kaxaml is invaluable.
Read Bea Stollnitz's article on how to debug data binding in WPF. Set your VS environment up so that you can always see the Output window while you're testing your UI.
Use MVVM and data templates from the very start. Pretend that code-behind doesn't exist, and that the only way to interoperate between the UI and the data model is through data binding and commands. You'll back away from this position pretty quickly, but if you make yourself learn this from the jump you'll find everything you do easier.
Pretend that your application needs to be able to run on a 36" widescreen monitor and a phone. Will you use fixed font sizes and measure things to the pixel? You will not.
Learn about the Grid's shared size scope and star-sizing. Those two things mean that you're going to use the Grid everywhere. The answer to the question "How can I get this element to use half of the remaining space on the screen?" is: with a Grid. (However, the answer to the question "How can I get this element to use all of the remaining space on the screen?" is: with a DockPanel.)
Be aware of the fact that WPF is not mature technology, and of the implications of that. It's not that it's buggy (it's not, though there are bugs) or has inadequate functionality (again, there are issues, but not often critical ones): it's that there are a lot of how-to-do-X-in-WPF articles and blog posts that were written before we really knew what was maintainable and what isn't. Validation's a great example. You can find no end of explanation of how to set up validation rules and attach them to bindings. You might not quite so readily find posts written later about why in most real scenarios you want to use IDataErrorInfo. Be even more hesitant about accepting the first answer you find than you normally would.
If you think that composability and dependency injection are obscure architecture-astronaut concepts with little application to real-world software development, get your head straight.
Don't freak out about how complicated dependency properties are. They can do a ton of things, but as a practical matter all you need to think about at first is change notification and value inheritance. Change notification requires a property setter to do something; that's built into SetValue. Value inheritance requires a property getter to do something; that's built into GetValue. The fact that property values can be either local or inherited means that instead of values being stored in fields, they're stored as dictionary entries; if a given property doesn't have a local value (i.e. there's no value for the property in the DependencyObject's dictionary), the DependencyObject looks to the parent to get its value. The terminology's really verbose, but the ideas are very straightforward.
I found this resource that provides several excellent examples.
Microsoft All-In-One Code Framework
Microsoft All-In-One Code Framework
delineates the framework and skeleton
of Microsoft development techniques
through typical sample codes in three
popular programming languages (Visual
C#, VB.NET, Visual C++). Each sample
is elaborately selected, composed, and
documented to demonstrate one
frequently-asked, tested or used
coding scenario based on our support
experience in MSDN newsgroups and
forums. If you are a software
developer, you can fill the skeleton
with blood, muscle and soul. If you
are a software tester or a support
engineer like us, you may extend the
sample codes a little to fit your
specific test scenario or refer your
customer to this project if the
customer's question coincides with
what we collected.
Today is March 12th, 2010. The project
has more than 360 code examples that
cover 24 Microsoft development
technologies like Azure, Windows 7 and
Silverlight 3. The collection grows by
six samples per week. You can find the
up-to-date list of samples in
All-In-One Code Framework Sample
Catalog.
http://1code.codeplex.com/
Consider looking into using the MVVM pattern.
I don't like to use XAML. I prefer to code everything in C#, but I think that I am doing things wrong.
In which cases it is better to use XAML and when do you use C#? What is your experience?
Creating an entire window in C# can be a mess of code. The best thing about WPF is that XAML allows you to separate your design from your logic, making for much easier-to-read code.
I'll use C# when I need to create dynamic controls, but I tend to keep my general design, static storyboards, styles, datatemplates, etc. in XAML.
Check out this video on MVVM in WPF. If you want wrap your head around how to organize a WPF application vis-a-vis what goes in XAML, code behind and other abstractions, this is a great place to start.
You can certainly go too far with XAML. Those who want their entire user interface (including logic, event handling relationships, etc) defined in XAML are probably missing the point.
The aim of XAML is to provide a common format for determining how things should look. It should just be a description of how to lay things out, how to color and style them visually.
There is really very little point in trying to use it as a replacement for other aspects of C#, because C# has a permanent head-start in terms of programming features - reuse (defining types and functions), referring to variables, procedural programming, and even declarative or functional styles.
Personally I really like throwing together a UI with a Linq expression!
The ultimate absurdity was reached by a sample I saw where they used workflow actions as the children of a button to supply the Click handler, so the whole program was in XAML. It sounds "cool", but the problem was that it was significantly more ugly and unreadable than the equivalent C# or VB.NET program, and so everything that is ready to use in C# has to be replaced by a more verbose, flaky equivalent. Nothing has actually been gained by this translation to an uglier syntax - it's the same program only more hideous. XML is a poor basis for the syntax of a general programming language. Start with the fact that the greater-than symbol has to be written as >!
In a parallel universe, Microsoft released C# 3.0 before they finished XAML. The XAML team adopted C# 3.0 object/list initializer syntax instead of XML as their syntax. And this whole debate never happened.
My experience is that some things are far quicker to do in C#, while most are quicker to do in XAML. When it takes 5 lines of C# code to do what a single line of XAML code can do, it's pretty easy for me to choose which is better.
Basically, XAML is meant for expressing visual-design, C# is meant for expressing logic.
Any visual design should be done in XAML, any logic should be implemented in C#.
- This enables giving the visual design to a designer to play on without worrying about changes to the logic and even replacing the entire visual design at run time using loose-XAML.
- This also means you could replace either the logic or the visual-design without "breaking" either.
- The connection between the two should be done with data bindings and with command bindings.
The practice I use is:
1. Define the model (the business data object model) in separate C# code.
2. Define the constant parts of the view (the constant parts of the graphical user
interface, e.g. the windows, menus, ...) in XAML (preferably use Blend and not VS for this).
* Do not define styling (colors, fonts, ...) here.
* Do not write event handlers for buttons (in most cases) in code-behind-the-XAML, use command-bindings instead.
3. Define how the model is presented within the view (the GUI for viewing/editing the data objects) using XAML "ResourceDictionary"s located in separate files.
- Write using blend then add bindings to XAML using VS (Jetbrains' Resharper add-on for VS will help with binding expressions).
- If the object types are not known during design-time you can use "loose-XAML" and place the XAML in a folder which can have files added to / edited within without recompiling.
4. Create a connection between the model and the view (a controller/view-model) in C# which:
* Creates views as necessary (for dynamics objects)
* Data-binds the view to the model (sets view's DataSource as the relevant object within the model)
* Implements the commands
* Command-binds the view to the command implementations within itself
5. In Application.xaml delete the StartupUri="MainWindow.xaml" and add Startup="ApplicaitonStartUp" instead.
Within the ApplicationStartUp() event handler:
* Load any loose-XAMLs you have
* Create the controller
* Create the main window
* Create the model
* Connect controller to model and main window
* Show main window
* (Save model, controller and main window into private fields here to make sure they are all kept alive)
6. Add styling (colors, fonts) to a separate XAML file under a ResourceDictionary (using blend for this or purchase a ready made XAML theme/skin file).
The urge to want to write your UIs in C# instead of XAML is really just a manifestation of how comfortable you are in XAML.
For me, is is a personal goal to write as little code-behind as possible. Quite simply put, code behind is hard to unit-test, but can (and usually does) include logic that doesn't get tested. XAML is declarative (like HTML) and doesn't include any logic, so there is nothing to unit-test. I keep my view code in XAML and I keep my view logic in my ViewModel (MVVM) which is VERY easy to test.
Once you become more comfortable with XAML, the more you will realize its benefits over view construction in procedural code... Using a pattern like MVVM, you take it a step further, and realize that code-behind is only useful in rare cases.
The most important thing to bear in mind is that XAML is for presentation. All your presentation should be in the XAML. If you have logic, you keep that out of your XAML - in your C#.
Imagine swapping out your XAML file with one that LOOKS completely different - but still uses the same data - that's where the division should be.
One of the nice things about XAML is the separation of presentation an logic. This separation is not just theoretical but also practical. I my case, most of the my UIs are now being handled by a designer. This designer uses blend and does not know C#, has no interest of learnning c#, and frankly should not need to. This designer is a true designer, an artist, that knows how to use those tools to make things look really really nice.
Basically my phylosipy is this, the more I use XAML, the less work I have to do on the UI because he can do it. This has worked well for us. I usually design my control to be lookless, give them a basic no frill look, use the DataContext to bind my object(btw DataTriggers are a great way to cut down on code). As a result, I will often checkin my code, come back the next day, synch it, and the UI will look completely different, but everything still work!!!
Of course, it took at least 1/2 year to get there, but now this model seem to work and our UI look Kick A##, our application earns high praise, and I do little work on the UI itself and get to work on cooler things. To make a long story short, I think the code behind might be a bit more developer centric and forgets a whole other group that can benefit, trive, and make a living using WPF, namely the designers.
Of course, there are still times when it takes a devloper to make XAML/WPF sing and dance, and sometime we need to educate the designers about the right way to do things, but I think its worth the investement pays off many times over in large scale projects (maybe not so in short one0
XAML , MXML all these stuff works as long as you are developing a simple UI with some average complexity . Once your UI gets complex and richer , the automatic data bindings will cause more trouble than their benefits . The purpose of XAML is not make programming easy , it is to seperate UI from logic so that tooling of UI can be easy ..
No Data bindings , No Event handlers .. assume that you will never see your XAML again and write code ..
XAML is presentation . Data binding is not presentation . its presentation logic. put all presentation logic in code behind (data binding and handlers). Developers own code behind , Designers own XAML . if you are a developer and if you are touching XAML , then move that part in to code behind .
we can write WPF apps without XAML too ..
Thanks
Vinoth Kumar R
(Had gone thru enough using Flex MXML data binding)
It's not just about you, it's also about your team, some of whom may be designers.
XAML and C# is a really good way to separate the logic from design as already described.
For a typical programmer the way of programming is really changed by using WPF, assuming that the programmer comes from a C++, VB, WinForms, ATL and MFC background, a background from were the UI was not as natural separated from the logic as with XAML and C#.
To get used to this way of programming it takes some time, but getting more and more experiance it gets really effective.
Before starting it is really good to learn the MVVM pattern and to run tutorials to understand the strength of the pattern, and also to get to understand its benefits.
WPF and C# applications based on MVVM pattern benefits:
1. User Experiance and Usability
Separating the logic from UI, makes it more natural to have a dedicated designer working on the UI design and animations. In that way the programmer can focus on the logic behind and the technical solution while the UI is designed by someone that knows design.
That has been a problem for many software companies, atleast in the industry that the programmers actualy are the once that are designing the UI as well and that has resulted in a lot of support, maintance and in effecive applications.
There is a higher probability that it ends up with more user friendly applications by have a person with Usability background focusing on the usage instead of the technical solution. There is really interesting book abbout such examples, User Interface Design for Programmers, by Joel Spolsky.
By using the MVVM pattern for XAML application there is a good chance we will see more user firendly applications.
2. Maintanence
Maintenance, which is cost a lot within software development.
It can feel that the MVVM pattern is a big overhead in the begining but while functions are added and the more complex and advanced the application is getting the more benefitial it is. You will see that it is really easy to maintaine such an application.
For an overview you can look into this video:
3. Mix of competences
Dedicated designer and a dedicated programmer working in a team to achieve a better result is a very good way of mixing competences. Instead of only hiring programmers organizations need to combine the competences to provide the best results.
4. Opportunity for design interested programmers
Finally it is possible to implement fancy applications in the Windows environment. If you are a programmer that are interested in design the Microsoft Expression Blend really opens up possiblities to learn and achive fancy, useful applications with a nice design.
There can though be risk using with XAML and C#, MVVM or not, the great possibilities and flexibility it provides can also be a drawback. Letting the programmer loose with this new easy UI environment, the applications may end up with a wide spectra of animations, colors, everything this new environment provides. Remebering how you added UI controls in the C++ and ATL envrionment.
Still the benefits are more and I hope you get some inspiration to use XAML instead of C# for the UI, when getting used to it I am convinced you will like it.
A link to a good tuturial:
Tutorial MVVM XAML C#
I originally came from the Web side of development and am learning WPF/Silverlight at the moment. For me, the XAML model makes much more sense to me than WinForms ever did. I treat the XAML as if it were HTML and the .cs files just like a code-behind.
I love clean code, the less code I have, the cleaner it is. Code can be written in millions of ways, XAML is more restrictive. XAML is good at cutting down code, when appropriate of course. If I can put something in XAML, I'll do it. Tools can read XAML and do stuff with it. Much less with code. Tools and frameworks handling XAML will evolve and get better, doing more and better work with existing XAML. Can't say that about code. The more XAML evolves, the more we'll be able to declaratively define our applications.
For me, using XAML is like using LINQ. If I can write a one line statement that is easy to read and let a framework decide the best way to implement what I want, I feel good. I definitely try, as much as I can, to use declarations of what I want instead of hardcoding how I want it to be done. F# is another good example of this paradigm.
All logic should be in code regardless what you programming language that you use in computer programming. XAML should never replace that even in ControlTemplate although it is nice but it is far much easier to unit test and debug code.
It seems no answers mentioned an important point yet:
https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh465340.aspx
XAML is just procedural code (only easier)
<Grid x:Name="ContentPanel" Margin="12,0,12,0">
<Button Height="72" Width="160" Content="Click Me" />
</Grid>
"The following shows how this XAML could be partially replaced by code written in C# or Visual Basic."
// Initialize the button
Button myButton = new Button();
// Set its properties
myButton.Width = 160;
myButton.Height = 72;
myButton.Content = "Click Me";
// Attach it to the visual tree, specifically as a child of
// a Grid object (named 'ContentPanel') that already exists. In other words, position
// the button in the UI.
ContentPanel.Children.Add(myButton);
If you worked with windows forms for example, you probably remember the windows forms designer generates a .designer.cs file containing code similar to the example from the link above. That kind of declarative code is much better represented in XAML than C#.
For any non-toy application you should ALWAYS prefer XAML to define UI and connect it to logic in a MVVM manner.
Some things are easier to maintain or debug in code.
Not to Mention that you will be able to do more in Xaml2009 that has to be done in code behind now.
Unfortantly BAML won't fully support xaml 2009 in vs 2010 time frame so you can't compile xaml in 2010 time frame. And will have to wait for a later version of blend to do the full dev design loop. (later than 3)
Douglas
XAML can be seen as being similar to a combination of XHTML and CSS or XML and XSL which are used for structure and design. Any form of logic should be in C#. This way structure and design are seperated from logic. Your code should be cleaner too by using this approach. Another positive thing is that tasks can be easier to separate between designers and programmers.
One more thing... this is the definition of XAML from MSDN:
Extensible Application Markup Language (XAML) is a markup language for declarative application programming. Windows Presentation Foundation (WPF) implements a Extensible Application Markup Language (XAML) loader and provides Extensible Application Markup Language (XAML) language support for Windows Presentation Foundation (WPF) types such that you can create the majority of your application UI in Extensible Application Markup Language (XAML) markup. In addition, the SDK includes a Extensible Application Markup Language (XAML) editing tool called XAMLPad. You can use this tool to experiment with Extensible Application Markup Language (XAML) in real time.
Link to quote.
Programming WPF in C# with a fluent style helps keep the code size and complexity down. See this answer for an example of using a fluent style with WPF.
It's mostly preference I think. I use WPF, since it's easier to structure different screens and separate the C# code logic from the UI. Typically all my logic is structured in another C# library than my UI which is the startup project in WPF or Windows Forms
My company has developed a long standing product using MFC in Visual C++ as the defacto standard for UI development. Our codebase contains ALOT of legacy/archaic code which must be kept operational. Some of this code is older than me (originally written in the late 70s) and some members of our team are still on Visual Studio 6.
However, a conclusion has thankfully been reached internally that our product is looking somewhat antiquated compared to our competitors', and that something needs to be done.
I am currently working on a new area of the UI which is quite separate from the rest of the product. I have therefore been given the chance to try out 'new' technology stacks as a sort of proving ground before the long process of moving over the rest of the UI begins.
I have been using C# with Windows Forms and the .net framework for a while in my spare time and enjoy it, but am somewhat worried about the headaches caused by interop. While this particular branch of the UI won't require much interop with the legacy C++ codebase, I can forsee this becoming an issue in the future.
The alternative is just to continue with MFC, but try and take advantage of the new feature pack that shipped with VS2008. This I guess is the easiest option, but I worry about longevity and not taking advantage of the goodness that is .net...
So, which do I pick? We're a small team so my recommendation will quite probably be accepted as a future direction for our development - I want to get it right.
Is MFC dead? Is C#/Winforms the way forward? Is there anything else I'm totally missing? Help greatly appreciated!
I'm a developer on an app that has a ton of legacy MFC code, and we have all of your same concerns. A big driver for our strategy was to eliminate as much risk and uncertainty as we could, which meant avoiding The Big Rewrite. As we all know, TBR fails most of the time. So we chose an incremental approach that allows us to preserve modules that won't be changing in the current release, writing new features managed, andporting features that are getting enhancements to managed.
You can do this several ways:
Host WPF content on your MFC views (see here)
For MFC MDI apps, create a new WinForms framework and host your MFC MDI views (see here)
Host WinForms user controls in MFC Dialogs and Views (see here)
The problem with adopting WPF (option 1) is that it will require you to rewrite all of your UI at once, otherwise it'll look pretty schizophrenic.
The second approach looks viable but very complicated.
The third approach is the one we selected and it's been working very well. It allows you to selectively refresh areas of your app while maintaining overall consistency and not touching things that aren't broken.
The Visual C++ 2008 Feature Pack looks interesting, I haven't played with it though. Seems like it might help with your issue of outdated look. If the "ribbon" would be too jarring for your users you could look at third-party MFC and/or WinForms control vendors.
My overall recommendation is that interop + incremental change is definitely preferable to sweeping changes.
After reading your follow-up, I can definitely confirm that the productivity gains of the framework vastly outweigh the investment in learning it. Nobody on our team had used C# at the start of this effort and now we all prefer it.
Depending on the application and the willingness of your customers to install .NET (not all of them are), I would definitely move to WinForms or WPF. Interop with C++ code is hugely simplified by refactoring non-UI code into class libraries using C++/CLI (as you've noted in your selection of tags).
The only issue with WPF is that it may be hard to maintain the current look-and-feel. Moving to WinForms can be done while maintaining the current look of your GUI. WPF uses such a different model that to attempt to keep the current layout would probably be futile and would definitely not be in the spirit of WPF. WPF also apparently has poor performance on pre-Vista machines when more than one WPF process is running.
My suggestion is to find out what your clients are using. If most have moved to Vista and your team is prepared to put in a lot of GUI work, I would say skip WinForms and move to WPF. Otherwise, definitely look seriously at WinForms. In either case, a class library in C++/CLI is the answer to your interop concerns.
You don't give a lot of detail on what your legacy code does or how it's structured. If you have certain performance criteria you might want to maintain some of your codebase in C++. You'll have an easier time doing interop with your old code if it is exposed in the right way - can you call into the existing codebase from C# today? Might be worth thinking about a project to get this structure right.
On the point of WPF, you could argue that WinForms may be more appropriate. Moving to WinForms is a big step for you and your team. Perhaps they may be more comfortable with the move to WinForms? It's better documented, more experience in the market, and useful if you still need to support windows 2000 clients.
You might be interested in Extending MFC Applications with the .NET Framework
Something else to consider is C++/CLI, but I don't have experience with it.
Thank you all kindly for your responses, it's reassuring to see that generally the consensus follows my line of thinking. I am in the fortunate situation that our software also runs on our own custom hardware (for the broadcast industry) - so the choice of OS is really ours and is thrust upon our customers. Currently we're running XP/2000, but I can see a desire to move up to Vista soon.
However, we also need to maintain very fine control over GPU performance, which I guess automatically rules out WPF and hardware acceleration? I should have made that point in my original post - sorry. Perhaps it's possible to use two GPUs... but that's another question altogether...
The team doesn't have any significant C# experience and I'm no expert myself, but I think the overall long term benefits of a managed environment probably outweigh the time it'll take to get up to speed.
Looks like Winforms and C# have it for now.
Were you to look at moving to C# and therefore .NET, I would consider Windows Presentation Foundation rather than WinForms. WPF is the future of smart clients in .NET, and the skills you pick up you'll be able to reuse if you want to make browser-hosted Silverlight applications.
I concur with the WPF sentiment. Tag/XML based UI would seem to be a bit more portable than WinForms.
I guess too you have to consider your team, if there is not a lot of current C# skills, then that is a factor, but going forward the market for MFC developers is diminishing and C# is growing.
Maybe some kind of piecemeal approach would be possible? I have been involved with recoding legacy applications to C# quite a bit, and it always takes a lot longer than you would estimate, especially if you are keeping some legacy code, or your team isn't that conversant with C#.