Related
I have a little program which I made with WinForms and now I want to make it again using WPF.
I'm new to WPF and I read that whatever you can do with XAML, you can also do without it, meaning using code only.
Of course that you don't have any XAML when using Winforms. Can I use the same code for the WPF application that I used for the winforms application and get the same result? Or do I need to create and edit XAML? What are the advantages of using or not using XAML?
Also, considering the past experience using Winforms, should I somehow change the way I'm thinking about design and implementation that worked for Winforms but are not that appropriate for WPF?
No you can't reuse code from winforms in WPF.
and even if you could, you shouldn't.
whatever you can do with XAML, you can also do without it
You should really use XAML to define the UI, and then use DataBinding and MVVM, which is a much more professional way of development than the traditional procedural winforms approach.
Not using XAML is much more troublesome than using it. It may look intimidating at first but it's a really awesome thing to work with.
Of course that you don't have any XAML when using Winforms
No, of course not. winforms is a really old technology that doesn't support anything. That's why they created the Visual Studio designer, otherwise no one would have ever used winforms for anything, because of the horrendous gargantuan behemoth amount of code required to do anything useful.
Can I use the same code for the WPF application that I used for the
winforms application and get the same result?
Probably, by adapting some class names and whatnot, but then you lose the main advantage provided by WPF, which is precisely getting rid of the horrible winforms-like code.
considering the past experience using Winforms, should I somehow
change the way I'm thinking about design and implementation that
worked for Winforms but are not that appropriate for WPF?
Yes. WPF supports MVVM, and that requires a really different mentality from the traditional winforms approach.
I strongly recommend reading Rachel's Excellent Post about upgrading from winforms to WPF.
I tried converting a Winforms app to WPF directly, and it causes way more issues than you need because you are fighting the framework all the time. Read up on MVVM and databinding and use that. Its what WPF is designed around, and comes with several advantages such as testability. You can actually get quite a long way with a few of the simple concepts (databinding, viewmodels etc...) and expand your knowledge as you go, but I'd recommend an understanding of MVVM and databinding in WPF first.
A good framework to get started with would be MVVMLight, but its worth writing the basics without a framework to get to know how things work first.
I seem to remember this being a good set of posts from reed copsey: http://reedcopsey.com/series/windows-forms-to-mvvm/
Trying to create WPF controls without XAML is asking for trouble - the whole framework is built around the MVVM pattern which demands that your View be described in a declarative fashion, rather than a procedural fashion. While you can definitely create same UI objects in C# and XAML, doing so in C# will require you to know (in truly excruciating detail) how the framework operates in order to compensate when the state of your UI changes. On the flip side, if you do it XAML (as WPF dictates you are supposed to), then things generally update just fine and without the necessity of working around endless bugs. In short "yes" you can do it in code, but "no" you can't do it in code without losing your sanity.
Actually it depends on how complex is your project. For quite a small project you can make this "conversion" quite simply. But it's not a good practice even because WPF development often is based on MVVM/Prism and they give you lots of advantages.
Also the behavior of your UI might be different - it depends on the complexity of your project.
I'll 2nd or 3rd or 4th the other answers. Never, ever, ever, ever, ever try to build a WPF app with "Winforms style" code. I did that on my first ever WPF app and it was the biggest mistake I've ever made. What a gigantic mess. The 2nd app I went half-way towards MVVM and that too was a gigantic mess. 3rd app and ever since I've gone 100% MVVM, DI, etc. and 100% by the book WPF and code is super clean.
There isn't really a point in porting Winforms code to WPF any way. The majority of the code you wrote in Winforms is thrown out when you go WPF. Basically the only portable stuff is the business logic. All the UI logic is completely different.
And you'll thank us later because one of the greatest concepts ever about WPF is the separation of UI and business logic. That makes swapping out controls a piece of cake.
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.
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