How do you manage huge and barely maintainable XAML files? - wpf

I'm having real difficulties with XAML files in Silverlight since they get very big very fast when using Blend. It just becomes a wall of text after only a handful of controls are added and animated.
I'm hoping a better vesion of Blend will come out soon, so that our designers will never even have to see XAML. For now, though, that is not a solution - XAML still needs to be managed manually and it is a depressing task.
Has anyone found a solution to this? How do you keep your XAML files in order? How do you understand them when they get big?
Edit: I am especially interested in Silverlight solutions, since the most obvious WPF solution - splitting things up into resource dictionaries - is not supported in Silverlight.

It does require a little bit of work to maintain XAML files, but basically, what you need to do is split them up in resource files (XAML Resource Dictionaries) using a scheme that makes sense to you.
For example we use a scheme where we have a folder structure like this:
Resources (contains XAML Files that represent the user controls and pages)
Stencils (XAML files with Shapes)
Styles ( XAML Files with styles)
Brushes ( ... )
Shared
Templates ( ... )
Your structure might vary but, separating all resources in different files really makes maintenance more easy in the long run.

I have been using Silverlight 2 since January when it was in private release, and we ran into this problem, all our XAML was in one big file. What we did as best practices was to break up the user interface into separate user controls based on visual categorization (header, footer, navigation controls etc..) Originally we tried to use nested canvases (grids had not been added to the framework yet) and this turned into a maintenance nightmare later.
In Blend you can actually select a Canvas/grid etc... from the Objects and Timeline window, right click on it, and you are given the option "Make Control.." This made for speedy re factoring and modularizing our main XAML file. We then used Events to allow the user controls to communicate between each other.
Hope this helps, and good luck!

I'm a Creative Developer and work in Blend extensively.
I published a few thoughts last year on keeping XAML clean.
Silverlight currently does not support MergedResourceDictionaries so it's hard to break out the XAML into separate ResourceDictionary files as I suggested in another post.
Paul Stovell also has some interesting guidelines for XAML.

Related

Unified XAML for WPF and Silverlight using T4?

I am writing code that is used in both WPF and Silverlight. In C# I can use "#if SILVERLIGHT" for conditional compilation, and it works.
In XAML, however, I must resort to use completely different XAML files, since some attributes are simply incompatible. XAML files are 99% a like, and keeping them in sync is a hassle.
I would like to convert them into a T4 template, so I can do things like:
<SomeControl <#=ClipsToBounds()#> />
Where ClipsToBounds() produces different text for WPF and Silverlight. The requirements are:
Intellisense while working on the XAML
Templates generated at build time
The project must be self contained and work on stock version of Visual Studio: installs of various SDKs and 3rd party editors are not
acceptable
Results of the template run should NOT be in source control. -
I found that I can change custom tool on a XAML file from MSBuild:Compile to TextTemplatingFileGenerator and I don't lose Intellisense. However, resulting templates are generated at design time. To have then generated at build time seems like a big pain.
Did anyone have successful experience with this kind of setup?
Only the generic user controls which have generic behaviors across the platforms can be placed in PCL , However,the best suggestion would be keeping separate xaml views for each platform .
Since nobody seems to have suggested a template based solution as desired, I'll share some experience of working with projects targetting both SL/WPF. Many people will suggest using two completely separate XAML files, a different view per-platform, and in many ways this is the "purist" thing to do. But if you want to eliminate duplication, and reduce the risk of your 2 targets drifting apart, I'd certainly suggest sharing the XAML files (with simple project links) can work acceptably well.
There are a few common incompatibilities:
Controls exist in both platforms in different namespaces - subclass your own version and refer to that.
Styles etc. need differ between platforms - include a common dictionary of resources, different per platform, and reference by key.
Controls are substantially different, or present in only 1 platform - introduce your own wrapper control (which may require substantial implementation in the 'missing' case).
Basic properties or functonality missing - can often hack something up with an attached behaviour (eg your ClipsToBounds example is found here).

WPF Blend tools vs hand-coded XAML for interface controls

Hi this might seem like a dumb question, but I was looking for a little feedback. I am designer working with a development team on a WPF application. We installed Expression Blend 4. I new to WPF/Silverlight, but I have jumped right in and I think it's great.
However, I did notice that xaml code that can get generated when using Expression Blend can sometimes be overly obnoxious. For example, I created a Control Template for a button with Blend and the markup was like 100 lines of code. Then I created my own control template that was only 20 lines or so and it did exactly the same thing. I did the same thing for a listview and wow, that amount of code that was generated for a ListView template was RIDICULOUS. So again, I created my own styles and templates and the result was A LOT less xaml code.
The app we are creating is going to be pretty big I guess, so my question is, is it that much of a concern for performance if I were to simply create all design/interface elements using blend GUI, even though the generated code can be a lot more extensive? I can see how using Blend tools for design can make things a lot easier, but just like when designing websites, I have never used design view in Dreamweaver because the code that gets generated is pure crap.
Any insight would be greatly appreciated.
Thanks a lot
Personally i would only use any designer for drafting and real-time display of the visual representation of my hand-written code. The generated code may not be horrible but once you need to go into it to do something manually you will have a hard time finding everything you need if you did not write it yourself. Also Blend slices things up quite a lot (create resource & reference it) while i like to nest things in place if they are only used once (i do not know if the code generator could be adjusted in that regard).
It should not be performace concern that the templates are big, if you just copy the default ones used they are quite huge themselves and it's not really an issue.
I'm guessing the control template you generated for the button didn't actually do the exact same thing as the default one which you copied in Blend. You may think it did, but I'm guessing it was missing something. For example, did your template handle all 9 visual states that are used by a button? If you had only 20 lines of XAML, probably not. And yes, the ListView control template is quite large because it's quite a complicated control under the covers.
In general, I wouldn't worry about generating large control templates. It's going to happen. The runtime handles this quite well, in general. Unlike Dreamweaver, Blend generally gives you pretty good code. Performance only becomes an issue if you misuse resource dictionaries by doing something ill-advised such as setting the build action to embedded resource in visual studio. (I believe this creates a loose XAML file which must be parsed and compiled at runtime instead of compile time.)
The key to maintaining your sanity is organization. Just like with a website, you need to come up with an organization scheme for how you're going to store your control templates.

How to speed up WPF development

I've been developing with WPF for many months now. It's a great framework and I'm able to do fancy, elegant stuff that would have been a lot more difficult with WinForms.
However, I do have the feeling that for normal "line of business" type of applications without any special UI requirements, it still takes me longer to code the UI in XAML than it did to drag-and-drop it in WinForms.
For example, in WinForms, I would just drop an additional label and an additional textbox on the form and arrange everything (using the helper lines) until it looks nice. In WPF, I'd start by factoring out the properties of the existing label and textbox into a style, so I can reuse them; think about the most suitable layout element, maybe refactor some dockpanels/stackpanels into a grid (or vice versa); try different values for the margins etc. Although I have a lot of experience in WPF, it still takes a long time.
I know that I could just forget about "clean XAML" and use the GUI designer in Visual Studio 2008 (which just absolutely positions everything inside a huge grid), but I fear that I would lose a lot of the advantages that XAML offers by doing that.
Have you experienced something similar? If yes, what did you do to speed up everyday WPF development?
What I do to speed up everyday WPF development:
Ignore look and feel for as long as I can. Ideally, tweaking alignments and margins and defining styles is the very last thing I do.
Use the DockPanel before using a Grid, and a Grid before using a StackPanel.
When using the Grid, star-size everything. I'll come back and fix this later, but during prototyping, having a clear idea of how many rows and columns the Grid actually has is enormously helpful.
Prototype in Kaxaml, finish in Expression Blend, test in Visual Studio. Figuring out a methodology for this has taken a lot of time, and it's still very much a work in progress. But Kaxaml is great for quickly seeing how a XAML prototype will behave, and Blend is great for working out the visuals and encapsulating things into user controls and styles.
When using Blend, don't create layouts in the artboard, create them in the object outline. When I'm first developing a WPF UI, the hierarchy of objects is a hundred times more important than how it looks on the screen. I'm still learning to do this, and it seems possible that once I get good enough at it I won't need to prototype in Kaxaml anymore.
Work on the smallest thing possible. This requires a lot of discipline. I've got a nice big complex XAML file, and I decide that I need to edit the template of a control The first thing to do is to create a tiny XAML file with that control in it, and edit the control template there. The temptation to work like this in situ is strong, as editing the control template is only a right-click away. Don't do it.
Don't even think about whether or not I should develop a view model for my tiny little one-off application. Yes, I should.
Learn Blend. Really, really learn it. Learn what all of the tiny icons that surround the selected object mean, and pay attention to them. (Here's a shortcut: I didn't set margins on that thing, but Blend did. That's the answer to maybe 30% of my "what the hell is Blend doing now?" questions.) Use the Blend UI even if I know it would be faster to edit the XAML by hand. This is again a matter of discipline, resisting the temptation to get it done now so that I can improve my ability to get more of it done later.
That's kinda like saying "Sliced apples are easy to make, but apple pie tastes better. How can I make apple pie as easily as I can slice apples?" Well, you can make it easier by using pre-made pie crusts or buying pre-sliced apples, but it will never be quite as easy, because lets face it, you're making something that's a lot more complex and potentially tastier.
It sounds like making styles holds you up. You could get off to a much quicker start if you just imported the same styles with every project. Usually I fly right along once I have all of my styles made.
Otherwise, the only way to make it as easy as the drag-and-drop WinForms designer is to use the drag-and-drop WPF designer.
I've been using WPF for a couple of years now - for optimal speed, I disable the design-view, use snippets, intellisense intensively (and of course ReSharper).
And then I make things simple - I have descided to use standard layout for almost everything - ie. main-screen bit -> DockPanel, ToolBar docked top -> snippet.
Popup screen -> DockPanel, ToolBar docked top, custom Persistent section docked bottom (Save and Cancel buttons) - properties of the viewmodel -> UserControl with grid, labels and properties.
For styling - first do that when I have at least 3 screens for each type - create resource dictionaries for each type. Define common stylings - Header textblock etc. Import ResourceDictionary in each screen and apply styles.
Apply coloring, margins, padding etc. in App.Xaml with non-keyed styles.
I can't think of a faster way. At least for me, I don't really need to think while doing it this way (so, I can use my brainpower later for the complex stuff) - and it gives a consistent "LOB-look" that is relatively easy to style, theme and change later on. It's basically a matter of typing.
My biggest challenge at the moment is that I'm constantly thinking of ways that the UI could be composed dynamically with data templates, which can often get in the way of simpler solutions when the extra flexibility is not required. Other than that, I've become faster now that I'm getting used to the different containers and their quirks. It's such a dramatically different technology that it's going to take time before I develop the appropriate mental tool set for my day-to-day UI tasks, especially since I still need to use WinForms regularly. I figure it's just a matter of time, however, before I have standard patterns in mind that I can deploy quickly and easily.
The advice about VS2010 is very good; its visual designer is actually useful, compared to VS2008's XAML designer, which was less than useless.
Microsoft's PR machine pushes the "Model-View-ViewModel" pattern extensively for line-of-business apps, to the point where they actually recommend things that can waste your time.
Do not spend hours trying to shoe-horn everything into XAML, unless your company or client has procedures which require it. If you can code it faster in VB or C#, and the code is still maintainable, testable, and readable, do it.
Do not become an MVVM purist; not even Microsoft has figured out the appropriate balance for this pattern, and even with the Silverlight 4 stuff, they haven't come up with a good set of development tools or best practices for the pattern, even though it's now been almost five years since it was first proposed; there are still very valid reasons to abandon ICommand and INotifyPropertyChanged in favor of just calling a method on your ViewModel from the code-behind. Also, no non-Microsoft WPF/Silverlight expert I've listened to in the past few months has failed to say, "I'm not sure about MVVM yet, I'm not a purist."
Find a balance and use XAML for what works for you, and C# or VB for what works for you. MS devs on their blogs are fond of calling XAML "markup", and C# or VB is "code, unfortunately". Well, if you're typing it in or laying it out, it's all code, and the truth is that all that XAML gets interpreted and then turned into C# or VB in files you can't see or readily edit, before it's compiled down. (For example, Application.g.vb is generated from Application.xaml as a partial class.)
There are XAML constructs like animations and storyboards which take many lines to lay out in XAML, but in the procedural languages might only take one or two lines of code and actually be easier to read, especially if the animation responds to an event under only certain conditions. Do what works best.
Also, if you're coding along and keep hitting run-time exceptions which make no sense, take a step back, find an alternate answer that gets you functioning, and implement it. Most XAML errors can't be caught by Intellisense or the compiler. It's possible to bang your head for weeks against a XAML problem, that can be coded in C# or VB with early binding in a comparatively much shorter time.
In short, relax and code to your own best practices, using the VS2010 tools, and you should be able to pick up speed.
If you use VS2010 I think the visual designer for the XAML is better now and I think brings the development time more in line with classic winforms development.
If you still need to target .NET 3.5 you can by setting the solution to compile to 3.5 instead of 4.0. This might be a good option for you if you aren't using VS2010 yet.
I feel your pain... Everytime we add a new field into the database, another TextBox/ComboBox has to be made on the form. I've found that using Expression Blend allows me to be much quicker at laying out the form. The downside is that using Blend tends to create more xaml than writing it by hand, so I usually end up cleaning up the xaml a bit.
In the end, Blend is a much better designer than Visual Studio (2010 included), so it's much quicker to do your design work in Blend, and development work in VS. (just my two cents)

Using the MVVM Light Toolkit to make Blendable applications

A while ago, I posted a question regarding switching between a Blend-authored GUI and a Visual Studio-authored one. I got it to work okay by adding my Blend project to my VS2008 project and then changing the Startup Application and recompiling. This would result in two applications that had completely different GUIs, yet used the exact same ViewModel and Model code. I was pretty happy with that.
Now that I've learned about the Laurent Bugnion's MVVM Light Toolkit, I would really like to leverage his efforts to make this process of supporting multiple GUIs for the same backend code possible. The question is, does the toolkit facilate this, or am I stuck doing it my previous way?
I've watched his video from MIX10 and have read some of the articles about it online. However, I've yet to see something that indicates that there is a clean way to allow a user to either dynamically switch GUIs on the fly by loading a different DLL. There are MVVM templates for VS2008 and Blend 3, but am I supposed to create both types of projects for my application and then reference specific files from my VS2008 solution?
UPDATE
I re-read some information on Laurent's site, and seemed to have forgotten that the whole point of the template was to allow the same solution to be opened in VS2008 and Blend. So anyhow, with this new perspective it looks like the templates are actually intended to use a single GUI, most likely designed entirely in Blend (with the convenience of debugging through VS2008), and then be able to use two different ViewModels -- one for design-time, and one for runtime.
So it seems to me like the answer to my question is that I want to use a combination of my previous solution, along with the MVVM Light Toolkit. The former will allow me to make multiple, distinct GUIs around my core code, while the latter will make designing fancy GUIs in Blend easier with the usage of a design-time ViewModel. Can anyone comment on this?
I checked your previous question and this one, and I had never really heard about switching projects to work in Blend and in Studio, and end up with two different UIs. I think this was not the intent of MSFT when they built Blend. Instead, the possibility to open the exact same project and code files in both IDEs (and all the discussions I had with the various teams at MSFT) hints that the intent was in fact to have one application only which can be edited in both environments.
I think that in the end, the goal is to have a variety of tools that you can use to edit your UI - XAML, Visual Studio designer, Blend. Depending on your role in the project (developer, designer, integrator) and depending on your ability with the tools, you can choose one or the other.
This doesn't mean that we never switch templates! Depending on the kind of application (for example between a SL4 desktop application or a WinPhone7 application), we use the same ViewModel (and below) code, but slap a different UI altogether on the files. I demoed how to do that in this video:
http://channel9.msdn.com/posts/kreekman/TechDays-2010-Understanding-the-Model-View-ViewModel-pattern/
This is the same talk I gave at MIX but extended by 15 minutes where I show how to reuse the ViewModel and model files, but use a completely different UI for WinPhone7.
Another application is switching templates when a window is resized (used very often in WPF, but also applicable to Silverlight) in order to show less details or a different layout for different screen sizes.
I hope that this reply doesn't confuse you :) and in fact, I'd love to hear your comments on that before we continue the discussion.
Cheers,
Laurent
I think MEFedMVVM would be a good candidate for this. It is simple and you can combine it with other frameworks.

What are your strategies for using Expression Blend on complex, decoupled WPF applications?

I've been doing WPF applications with the MVVM pattern using Visual Studio, coding C# and XAML mostly by hand.
Now I've gotten up to speed with Expression Blend so that I can click together WPF applications quickly just using the GUI, which is very nice, much more control of the layout than fiddling around with all the XAML elements 80% of your time.
But it seems that my applications in Expression Blend are simpler and necessarily coupled, using events that are handled in the code behind, etc.
I find it hard to imagine how I would go from this simpler approach of Expression Blend to a decoupled MVVM application with Views, ViewModels, routed events and commands, etc. other than to just take my whole project into Visual Studio and rearrange it to the point that I couldn't really edit it visually anymore in Blend, but would be back to using Blend to create little pieces of XAML that I paste into Visual Studio.
For those of you who are working with more complex applications with Expression Blend, what are your strategies for keeping your projects decoupled in an MVVM way, yet at the same time structured "in the Expression Blend way" (where you can still see and edit whole parts of your application in a way that makes sense visually) so that you can continue to edit them in the Blend GUI as they scale?
I've been using Blend first and foremost as a rapid-prototyping tool. For this purpose, I really like it. In particular, I find it very helpful when I'm not sure how to set things up to get the layout/behavior that I want.
I rarely edit my main project files directly in Blend. I find it creates markup that is unnecessarily complex or verbose. Also, as I become more familiar with WPF/XAML, I find myself using Blend less and less.
I have been using Blend for the UI of my projects since version 1. Being that my goal is to fully integrate the designer to the project, I have plowed through whatever gets in the way of this goal. While not being aware of MVVM for some time now, I naturally arrived at the same conclusion, and have been making ViewModels without knowing there was a pattern for them. Now with the help of others that are working towards MVVM, it's getting better all the time. I have now developed 3 applications with rich UI and functionality where all the UI was done in Blend.
Read Josh Smith's MSDN article, look at Jason Dolinger's work, and Karl Shifflett's work to mention just a few.
Look closely at using ICommand, INotifyPropertyChanged, the ObservableCollections.
Also, look for how you can manipulate controls from your ViewModel. As an example, there is ICollectionView. Assume that you have a list of animals, and you have a set of types that you want to filter them by (birds, mammals, etc.)
By using ICommand and ICollectionView, you could expose enough control where a designer could construct a listbox to show the animals, and a menu to show the filter list. There is enough functionality in ICollectionView to know what the current selection is, and if you had ICommand-based commands for "SortByBird", "SortByMammal", etc then when the designer made the menu, it (assuming the window's context was your ViewModel for this window) would supply the designer with the proper options to bind to.
I am currently working with another team at my company explaining how my projects have been set up, and they are responding positively to the new role of the designer using Blend.
I have not been able to successfully use Blend end to end for that.
I find in the general case, it's faster to edit xaml by hand in VS (exception would include anything with non-standard brushes for example). Blend is very click-happy, and it's not really fast to top it off.
Another area where Blend is really useful is creating styles/templates from existing controls.
Other than that, I'm not sold yet. Its capabilities drop when using code-instantiated datacontexts so it's no help there, and it tends to generate useless markup, static sizes and such, which I really don't like.
Blend is great for giving you an idea about how things can be done, but the xaml it makes is terrible and tightly coupled. As you learn the xaml side of things better you'll find it's much faster to just write the xaml than use Blend. Until you get to that point you can make your changes in Blend but then you should refactor the xaml it creates to make it less tightly coupled and take out the extraneous UI elements.
I'm a little late to this party, but hope that someone can still respond. I've yet to find a search result that outlines the process for drawing a line between the designer and programmer. The first part of it is MVVM so there isn't any coupling between the GUI and the underlying "business logic", and I'm working hard on learning that right now. The other part that I haven't seen anyone write about is, how do you actually go about designing a project in Blend so that the developer can basically give you a GUI DLL of sorts, and then your application's GUI magically changes?
Here's what I'm looking for -- the developer writes his code as usual, and also writes a very basic GUI that proves everything works as expected. Meanwhile, the designer is creating his cool little GUI with all of the usability features people have come to expect. Now, the developer can run his application with his GUI, but then can also switch to the designer's GUI on the fly.
I guess if it can't be done on the fly, does that mean in the ideal case that the developer would have his VS solution include the XAML from the Blend solution? Then in App.xaml just reference a different start file?

Resources