How does JavaFX compare to WPF? [closed] - wpf

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm mostly a C# programmer, I stopped writing Java about 10 years ago, but I try to keep up with the technology in Java by reading articles, talking with friends, etc.
I've heard about the new rich GUI framework called JavaFX, but couldn't find any resource comparing it with non-Java parallels.
Since I'm very familiar with C# and WPF, I'd like to get a feel about how similar or different the two technologies are.
EDIT: Seeing as there's no answers coming, I'll try to be more specific:
WPF uses XAML to create the visual tree, does JavaFX have something similar?
WPF is best used with binding to a view model in an MVVM pattern, does JavaFX also make extensive use of binding?
WPF utilizes the GPU for rendering, does JavaFX do the same?
How does Silverlight compare to JavaFX when run through a browser on a net pc?
... More to come...
I'm changing this to community wiki so that the comparisons can keep getting updated (hopefully).

I have been learning JavaFX for the last couple of weeks. Here is a high level overview of how it compares to WPF in my eyes:
All of my comments are related to JavaFX 2.0. This information will probably be subject to change as the platform is still fairly immature and is being actively developed.
Graphics
Like WPF, JavaFX uses a retained graphics rendering system. The user interface comprises a scene graph which is composed of 'nodes' which can be thought of as conceptually similar to WPF's UIElement.
JavaFX will offload the graphics rendering to the GPU if available. The graphics system uses DirectX on Windows and OpenGL on other platforms.
Markup
JavaFX user interfaces can be created both in code and via FXML markup which is similar to XAML in that the object graph can be created by nesting elements.
FXML has some similar features to XAML such as property binding (simple expressions only) and binding to event handlers (any onEvent method). Event handlers can be declared in-line but typically you would bind to an event in the associated controller.
FXML files can have an associated controller which allows you to declare complex event handlers and to set up bindings between properties. This is a controller in the MVC sense and is not the same as a viewModel in the WPF world (typically a controller will have references to nodes and controls).
One difference to WPF is that it appears that the FXML is not compiled into an intermediate binary representation like BAML. I haven't noticed any performance issues yet but have not used the system extensively. I have noticed though, that FXML usually tends to be shorter than any XAML as the platform still encourages you to write code and styles are declared separately.
An introduction to FXML can be found here.
A scene builder is provided free (as in beer), so if you don't like hand coding the UI you can drag and drop elements, set properties and bind to code in your controller and the FXML will be generated automatically. Obviously the scene builder is nowhere near as powerful as Expression Blend but it is still better than the 'designer' provided by Visual Studio.
Binding
JavaFX has a very powerful property and binding system. The Java Bean pattern has been extended to include classes that encapsulate a property (similar to the way WPF dependency properties represent properties). These classes implement interfaces that provide invalidation and change notification.
There is a distinction between invalidation notifications and change notifications. Invalidations just tell you that the binding expression is now invalid and needs to be recalculated; the recalculation does not actually occur until you request the property value via its get() or getValue() methods. If you have registered a change listener, however, then the expression will be re-evaluated immediately and anything that is bound to that property will reflect the changes.
JavaFX exposes these properties in a similar way to WPF with a get and set property and a method that returns an instance of the property wrapper (which are not static like WPF properties).
Complex bindings can be created between multiple properties. Want an integer property to be the sum of two others (a = b + c)? No problem, JavaFX provides a Fluent API to express these kind of relationships E.G.
A.Add(B, C);
If the value of either B or C changes then the appropriate notifications will be raised so that the system knows that A needs to be re-evaluated. Note that in this case, an exception will be thrown if you try and set the value of A as it is bound to the other properties so it does not make sense in this context.
These expressions can be fairly complex E.G. a = (b + c) * (d - e) and can include any number of properties. The fluent API is fairly easy to read and use but is not as nice as some of the Fluent API's provided by some of the Microsoft libraries but this is more down to the Java language limitations rather than JavaFX itself.
Simple bi-directional bindings can be created between properties of the same type so that if one is updated the other automatically reflects the change.
JavaFX also provides a low level API to customise bindings yourself if you want to create a custom binding expression that is not provided by the API or if you are concerned about performance.
One of the biggest differences between JavaFX and WPF is that bindings are primarily carried out in code in JavaFX vs. the WPF way of establishing bindings in mark-up.
An introduction to properties and bindings can be found here.
Styles
JavaFX uses CSS to change the looks of the nodes contained in the scene graph. There is a full specification available which explains the types and the properties that can be set on each node type.
JavaFX also provides some additions that help to improve CSS such as variables that can be defined and used elsewhere E.G.
.button {
my-custom-color: RGB(234, 44, 78);
}
.my-control {
-fx-background-color: my-custom-color
}
It also provides a couple of functions that allow you to derive colours from other previously defined colours which is useful for creating things like gradients. This means a base palette of colours can be defined and the rest can be generated from these values (this is what the default JavaFX CSS file does).
JavaFX CSS does not allow you to define the type of layout used by a node (as of writing this all layout needs to be performed in code). This works really well for me as this was the one aspect of CSS that really caused me pain when using it with HTML.
Personally I prefer CSS to XAML styles which tend to be too verbose for my liking.
A guide to JavaFX CSS can be found here.
Layout
JavaFX provides a number of layout panes that are similar to those provided by WPF. One difference I have noticed is that the measure and layout contract is defined further up the inheritance chain in the Region class.
As previously mentioned, Layout cannot be carried out using CSS but can be expressed using the code, FXML or created using the scene builder (which is ultimately converted to FXML).
Controls
JavaFX provides an ever growing library of controls that we have come to expect. One major difference between JavaFX and WPF is that the controls are essentially black boxes and cannot be re-templated in the way that WPF controls can. They also seem to expose far less properties than the WPF controls.
The controls do expose some of the implementation specific regions to CSS allowing specific areas of a control to be targetted by your styles. This is known as the substructure of the control. E.G. a CheckBox exposes two substructures; the box and the check mark allowing each part of the control to be styled independently. Note that as described earlier only the look of a control can be altered using CSS but the feel cannot. E.G. you cannot dramatically alter the way a TabPane lays out its content by altering its internal layout panel in the way you can with the WPF TabControl.
Whilst this sounds fairly limiting, the preferred way of creating custom controls in JavaFX seems to be using composition along the lines of deriving from a layout panel to position standard controls and re-styling them using CSS.
Conclusion
Overall I am very impressed with what JavaFX has to offer at the moment. Whilst it is no where near as mature as WPF it is being actively developed and Oracle certainly seem to be backing this. Time will tell if it's successful or not.
I would recommend giving JavaFX a try. Read the documentation and try putting together a small application and see what you think.
You should also check out FXExperience.com which is updated regularly with information from the development team.

I think the best way to to get a feel for JavaFX is to just try it out. There are some good tutorials on the JavaFX website. Here's a couple:
The JavaFX language
Creating a UI in JavaFX
They are pretty quick and give you a good feel for the language. There are many others on the JavaFX site if you are interested in more tutorials and articles.
For specific answers to your questions:
JavaFX has it's own declarative language for creating the "visual tree" which is not an xml derivative. The UI is based on a scene graph so you can apply various effects and animation to any node in the graph. See the tutorials for more information. There is also a designer tool for JavaFX (which I have not yet tried).
JavaFX has binding built into the language.
JavaFX on the desktop uses Java AWT/Swing which does use GPU rendering. Every version of Java seems to offload more of its graphics to the GPU. Chris Campbell from Sun has blogged some about GPU acceleration. I'm not sure if the mobile version of JavaFX has GPU acceleration. I found that earlier versions of JavaFX weren't performant enough for what I needed, but I know the latest version does have significant performance improvements over previous versions and they are still working on making it faster.
JavaFx uses Java Applets to run in the browser. As of Java 6 update 10, the Java applet framework has been reworked and though it is not as seamless as Adobe flash, it is much improved. I'm not sure how it compares to Silverlight other than I've had trouble getting Silverlight to work on Linux, but did get JavaFX working on Linux.
Here's another related question.

Related

Automation: Why WPF based CEFSharp uses Bitmap for rendering while winforms does not?

We were able to use automation tool and it was able to identify html objects on Winforms while on WPF it does not since it is rendered as an image.
My main question is what does Winform CEFSharp uses to render and why WPF not able to use a similar rendering mechanism?
Warning: it is a very generic answer. I briefly looked at CEF source (briefly - 3-5 minutes) and the rest are my guesses based on my own WPF/WinForms interop experiences. I've had quite a few. I also played a bit with early Chromium builds. However, all of that was a few years ago, so it may simply be out dated. Maybe Chromium has now first-class WPF support. I have not found any information about that, but if this really happened, I encourage you even stronger to follow the last paragraph.
--
I doubt that there is any reason behind this other than time-cost to implement -
either on CEF or Chromium project.
WinForms and WPF are totally different GUI frameworks, written in different eras, using different architectures, different rendering techniques, different platform features, etc. This is as different as it can be, down to the idea of a "Window" itself.
In WinForms, almost every control is a separate small window-like thing, has a system-wide handle, has a system-tracked region, etc. All controls render themselves almost directly by unmanaged win32 GDI+ functions.
In WPF they don't. In WPF there's only one handle per whole window, controls don't render themselves. Instead they have a definition of their "look" and the WPF renders them to the 'surface', which is then blitted/streamed (sorry, dont remember) to target device.
That's true that CEF uses different approaches. For WinForms they make heavy use of a 'browser component' taken directly from Chromium, for WPF they render to bitmap and show/update the bitmap periodically.
Why? My guess is that it's because Chromium already provided a COM/OCX/ActiveX/whatever component, and WinForms can use it almost directly, thanks to the everything-has-a-handle "feature" - if you can call it a feature - one of the goals and successes of WPF was to eliminate that.
However, I don't think that Chromium at that point of time provides any such component for WPF.
If it does not exist, then for WPF there are only two options - one could embed the WinForms component in WPF window through a special 'host' intermediate control, but that actually hits the performance and also has many problems when some advanced rendering features (like movie streaming) are used. Diagnosing and fixing them is complex, hard, and even unstable (crosshosted components behave very differently on different windows and .net versions, even on .net patches sometimes change them, it can work one one, and freeze on other, hang and render as black on next and cause a blue-screen on another)
Other option for WPF is to use the "offscreen" mode. Chromium can render to a bitmap, so why not. Render to bitmap, and display that. Simple. Quick. No problems.
So, I'd say, it all boils down to a famous quote from Eric Lippert:
The question is "why does [snip] not have this feature?" The answer to that question is always the same. Features are unimplemented by default; [snip] does not have that feature because no one designed, implemented and shipped the feature to customers.
It's great we can at least display Chromium in WPF apps. If you think it can be done better and that it's worth doing, it's open source, feel free to implement it - if not in CEF, then in Chromium itself.

Difference in display of WPF and Windows Forms applications

Actually, I have started learning WPF. I have few months of experience in developing Windows Forms applications. Though, I am getting the meaning of a WPF application, but still I am not able to differentiate the difference between two, on the basis of their output.
With reference to this Link: Device Independent Pixel (DPI), I have learnt that whenever the operating system render a WPF application it manages its size itself according to its resolution.
So to check this difference, I created two demo applications in both frameworks and changed the resolutions as well.. but I didn't find any satisfactory difference. Which could explain it is a WPF application and this one is a Windows Forms application.
It does not create any scroll bar on maximizing and doesn't make the button big or small on changing the resolution.
I have read somewhere that Visual Studio 2010 has been rewritten in WPF. But in my experimentation I saw that, (on changing the resolution of desktop) it makes text and graphics unreadable/blurry. On re-sizing its window, everything was getting hidden except the menu-bar. And the menu-bar content was shifting its positioning, e.g. far right one menu items were shifting down. Why?
Kindly make me correct & explain a little more bit (this display issue) too.
To answer this question properly I should write a whole chapter, but I keep it short:
There are three major differences between a WPF application and a Windows Forms application: Layout, Render, Presentation
Layout:
WPF layout system provides a greater flexibility in arranging the elements on the fly. It is based on the Element Bounding Box (as opposed to precise pixels in WinForms) and Measure and Arrange mechanics (as opposed to UpdateLayout in WinForms) that automatically and dynamically finds the place for each element without any need for a manual update.
Basically, all elements bounding box are measured first and then are arranged using multiple methods such as Measure, MeasureCore, ArrangeCore, MeasureOverride, etc.
Unlike WinForms, where you have a pixel-perfect size for everything, in WPF you have much more options and complexity such as Width, ActualWidth and DesiredSize (and even Transforms as LayoutTransform) for the same element.
This is why
As you type in a WPF TextBox, its width might increase and push other elements away or even push some elements into a new row (like the menu bar you've observed)
As the size of a control changes, it affects the available space for other elements. So their size and location might change accordingly.
When the window is being re-sized or resolution is changed, it immediately updates the layout and changes the size of elements in order to fill or fit the space. Here you'll find out more about Layouts.
using Margin alone (without using layout capabilities) to arrange elements is not the best idea in WPF. As it's the WinForms mindset which isn't much helpful while developing WPF.
Render:
WPF uses double data type for Layout (as opposed to pixel-perfect WinForms) and therefore you might see the edges blurry sometimes, but it can be avoided with SnapToDevicePixels=true.
WPF is much more efficient in utilizing the GPU to render a GUI. Try a grid of 30x30 TextBoxes in a Windows Forms application and a WPF application. No matter how messy you write the WPF, it never blinks and it still runs much faster than Windows Forms. Even adding a handful of animations, visual effects and styles on them does not hurt your performance like in Windows Forms.
Remark: To avoid a speed decrease and blinking in a Windows Forms application, you should set DoubleBuffer of the form to "true".
You can use any Transform as RenderTransform to easily implement smooth zoom/rotate, or develop custom GPU-based shader effects, and much more in WPF. (I think everyone agrees that doing such things in WinForms is feasible but real pain and you most likely will give up and move to GDI+ or DX if not out of frustration then because of the bad performance.)
And the last and the most important:
Focus on presentation:
When develping WPF Applications you have to stop thinking in Windows Forms: No more UI events, accessing controls by their names and writing logic in code-behind and start to think in WPF: Binding, Commands, Resources, Styles, Templates, Converters, DependencyProperties and their callbacks.
The real power of WPF lies in separation of 'View' and 'Logic', Which can be achieved using the MVVM pattern.
It makes the most visually-complicated problems quite simple and easy to develop and easy to write Unit Tests for.
Once you got the hang of it, you will realize there's no limit in how you can present the data or show off an awesome GUI looks.
If you've planned to switch to WPF, you've made the right decision. Always stick to MVVM and AVOID CODE-BEHIND AT ALL COSTS! (i.e. unless you are doing a pure UI operation: do not write code in .xaml.cs files, do not access x:Name in cs files and avoid UI events.)
Windows Forms (WinForms) and Windows Presentation Foundation (WPF) are two different ways of building the user interface for your application. Windows Forms is the older technology and its controls are found in the System.Windows.Forms namespace. WPF is a newer technology and its controls are found in the System.Windows.Controls namespace.
WPF
Pros:
Powerful styling and skinning structure
Easy to create your own look and feel
Does support Windows Forms
The future technology for developing Windows Vista applications
The ability to reuse existing code
Highly advanced data binding possible
Cons:
Declarative vs. procedural code
Requires .NET Framework 3.0
Compared to Windows Forms, still in development phase
Requires Dx9 compatible video card for advanced graphics
Windows Forms
Pros:
Extensive documentation to be found on the Internet
Plenty of examples
Does support WPF
Cons:
How long will this be supported? (I've read somewhere that Microsoft is just developing WPF now, only maintenance for Windows Forms).
Design your own look and feel in an application is a lot of work.

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.

Are WPF more 'flashy-like' than winforms?

I just installed visio, and the installer almost seemed like it was built in flash.
The buttons kinda glowed when I hovered over them, and when I clicked on 'continue' the form phased out in a cool way.
I'm assuming it was built in WPF.
Anyhow, so are WPF more flash-like (visually speaking).
Do they have new properties where you can make forms phase out nicely/smoothly compared to winforms?
Disclaimer: I work for Microsoft. However, I don't work on Visio, WPF, CLR or Silverlight team. So, the following is my personal take on these technologies. If you want to quote me, don't do it implying it's the official Microsoft position. :-))
Update: Anything I say below about Flash/Flex/AIR might be wrong, as I have not worked with these technologies and what I know about them is based on what I read on the intertubes. :-) If you notice anything wrong, just shout in the comment and I'll correct it.
To the best of my knowledge, the Visio installer is not built with WPF. It's all unmanaged code; it's just people took a lot of care to make it really polished.
WPF is the new UI platform for building standalone applications for the Windows OS. It supports a declarative UI language - XAML, and related CLR types to program against. WPF is a different platform than WinForms, although it is possible to build applications that mix UI built with both. WPF supports a lot of things that WinForms does not, like bitmap effects, animations, control styling and so on and exposes them both in XAML or through code. Also, WPF relies heavily on vector graphics, as opposed to the pixel graphics in WinForms. In short, WPF is quite powerfull and allows building very snazzy UI. (Don't take my word for it, though, as I am biased; go check around for what people are saying about it or buiding with it. :-))
WPF and WinForms do not compete with Flash/Flex. WPF and WinForms are both UI frameworks for building standalone client applications. As far as I know, Flash/Flex are frameworks for building rich internet applications - RIA (though lately people started interpreting this abbreviation as rich interactive applications).
Adobe did come up with AIR about half a year (or maybe a year) ago, which allows building standalone client applications, so you could say that Adobe is trying to position Flash/Flex/AIR to compete with WPF. Of course, that's my take on it and I doubt Adobe's official positiong is anything like that.
If you want to compare particular MS technnologies with Flash/Flex, take a look at Silverlight - it's the MS RIA platform.
Silverlight is related to WPF in the sense that they share XAML and the corresponding CLR types. Silverlight supports only a subset of what WPF offers, though, as it is not targeting Windows OS only and thus is limited by the fact that it has to be portable.
Quick update to reflect the changes in the year since I've written the answer :-)
With Silverlight 3 shipped, SL and WPF are getting even closer and sharing bigger set of supported features. In addition, most of the new XAML controls are built for platform at the same time. Thus, SL/WPF are getting to a point of singularity...
Also, SL 3 supports out-of-browser applications. In that sense, SL is not only starting to compete with Flash/Flex, but it is also encroaching on AIR's turf.
And no, I still don't work on the WPF or Silverlight team. :-)
WPF is being used as a replacement for WinForms, and as a competitor to Flash in the form of Silverlight. WPF consists of an entirely new object model that sits on top of DirectX (at least the desktop version). You can create WPF windows, controls, etc, entirely using C# or another .Net language just like you can render WinForms. However, Microsoft has also created a markup language called XAML (eXensible Application Markup Language). Nodes in an XAML document (XML) map to objects in a similar fashion to the way ASP.Net maps to web controls. XAML typically exists in a .Net project alongside a code-behind style C# file (or VB.Net or whatever). The C# file interacts with the objects generated by the XAML. This is fairly consistent with the "graphics via markup, logic via code" model that Microsoft and others are pushing.
One of the overlooked features when discussing WPF is the completely awesome data-binding that Microsoft wrote for WPF. The new data binding framework is a quantum leap beyond Windows Forms 2.0 data-binding. Microsoft added a couple of new interfaces that make it much easier to make an object or collection emit data-biding events properly. They also provided a very rich set of data-binding classes. You can bind anything to just about anything else. You can bind one-way data to control, control to data, two-way control to data and back, control to control, etc.
Back on the graphics side of the house, WPF makes it fairly easy to make an existing control look like anything. WP lets you compose your own template for what a class of buttons should look like, or one button, or all buttons. Or radio buttons. Or labels. You get my drift. Imagine if CSS included the ability to define what an input button would look like using other HTML controls.
They also provide a number of layout controls. You can continue to use exact positioning like in WinForms, or you can leverage of variety of techniques to make your window act more like a web page that grows and shrinks with resizing, etc.
The downsides: It is too easy to create spectacular effects that crawl on slower machines. Some of the graphics do not take advantage of hardware of graphics cards, though Microsoft has incrementally improved support for this. I believe when 3.0 first came out drop shadows were rendered purely using software. I think 3.5 or 3.5 SP1 changed it so that WPF would utilize graphics hardware for the task. Microsoft has said they will continue to enhance WPF in this fashion.
WPF is .Net 3.0 and above, which runs on XP SP2, Vista, and Servers 03 & 08. So don't plan on deploying WPF to a customer with Win2k desktops.
Summary: If you are doing desktop programming in .Net, you should be doing it in WPF unless you are targeting Win2k. You can avoid the downsides of WPF, and there are many upsides. Microsoft will probably throw away WinForms in some future release, or at very least you will stop seeing new features, etc.
As far as Silverlight goes, the betas for SL 2.0 look good. I think that Silverlight will require some wide-spread adoption. Microsoft has already tried to get this going. The NBC Olypmics site used Silverlight, and Major League Baseball uses it for its MLB.tv product. As soon as Silverlight gets a good install base I think you will see the Microsoft side of the development world starting swinging away from Flash and to Silverlight.
Edit after using Silverlight 3 and MVVM:
I have moved away from WPF and am doing a lot of Silverlight 3 development. But I think my comments here will still apply to the WPF developer.
I have been using the MVVM pattern in my app (think MVC with a twist). The Microsoft Patterns and Practices team has released a set of libraries known as Prism that supports various aspects of MVVM. There are WPF and Silverlight versions. Take a look at MVVM and Prism if you are going to be doing WPF or Silverlight development.
You can do a lot of flash w/ Winforms, or with custom components. But if you want out-of-the-box bang-whizz availability, WPF is the way to go.
Yeah, I think the intention is to be flash-like, it seems to me that MS has set its sights on taking down Adobe.
The way I see it: WPF is to Flash as WinForms is to Flex. WPF has more emphasis on vectors and states than on programming.

What's the best approach to printing/reporting from WPF? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I have an upcoming project which will have to be able to print simple reports from its data. It'll be WPF-based, and I'm wondering which way to go.
I know that WPF introduces its own printing technology (based on XPS) which looks quite easy to use. However, part of me wonders whether it would just be easier to use the ReportViewer control and embed it in a Windows Forms host control, since that will give users the ability to export to a variety of formats as well as print.
Has anyone had any experience with printing/reporting from WPF? Which direction would you recommend?
Limitations of RDL
I originally went with RDLC/ReportViewer for printing with WPF but found it very limiting. Some of the limitations I found were:
RDL could only create the most boring of reports
It was much more work to create a report using RDL than in straight WPF: The design tools are very primitive compared to Expression Blend and RDL deals only in tables
I didn't have the ability to use ControlTemplates, DataTemplates, Styles, etc
My report fields and columns could not effectively resize and rearrange based on data size
Graphics had to be imported as images - it could not be drawn or edited as vectors
Positioning of items required code-behind rather than data binding
Lack of transforms
Very primitive data binding
Printing directly from WPF is very easy
Because of these limitations I looked into creating reports using pure WPF and discovered it was really quite trivial. WPF allows you to implement your own DocumentPaginator subclass that can generate pages.
I developed a simple DocumentPaginator subclass that takes any Visual, analyzes the visual tree, and hides selected elements to create each page.
DocumentPaginator details
Here is what my DocumentPaginator subclass does during initialization (called when first PageCount is fetched, or during the first GetPage() call):
Scans the visual tree and makes a map of all scrolled panels inside ItemsControls
Starting with the outermost, makes items in the ItemsControls invisible last to first until the Visual fits on a single page without any need to scroll. If the outermost can't be reduced enough, reduces inner panels until it succeeds or has only one item at each level. Record the set of visible items as the first page.
Hide the lowest-level items that have already been shown on the first page, then make subsequent items visible until they no longer fit on the page. Record all but the last-added item as the second page.
Repeat the process for all pages, storing the results in a data structure.
My DocumentPaginator's GetPage method is as follows:
Look up the given page number in the data structure generated during initialization
Hide and show items in the visual tree as indicated in the data structure
Set PageNumber and NumberOfPages attached properties so report can display page numbering
Flush the Dispatcher (Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(() => {} ));) to get any background rendering tasks to complete
Create a Rectangle the size of the page whose VisualBrush is the visual being printed
Measure, Arrange, and UpdateLayout the rectangle, then return it
This turned out to be quite simple code, and allowed me to turn practically anything I could create with WPF into pages and print it.
Additional reporting support
Now that my paginator is working, I no longer have to worry very much about whether I am creating my WPF content for screen or paper. In fact, often UI that I build for data entry and editing also works very well for printing.
From there I added a simple toolbar and some code behind, resulting in a full-fledged reporting system built around WPF that was far more capable than RDL. My reporting code can export to files, print to the printer, cut/paste page images, and cut/paste data for Excel. I can also switch any of my UI to "print view" with a click of a checkbox to see what it will look like if printed. All this in just a few hundred lines of C# and XAML!
At this point I think the only feature RDL has that my reporting code doesn't have is the ability to generate a formatted Excel spreadsheet. I can see how this could be done but so far there has been no need - cutting and pasting the data alone has been enough.
From my experience my recommendation would be to write a paginator, then start using WPF itself to create your reports.
We had this same issue, and ended up using RDLC/ReportViewer for now. There's no native WPF reporting tool (that I know of) and RDLC is pretty simple to use, and is free. The runtime overhead for it is small (around 2Mb) but you must remember to distribute it as it isn't part of the .NET Framework.
Look at http://wpfreports.codeplex.com/
Take a look at PdfReports. It's a code first reporting engine, which is built on top of the iTextSharp and EPPlus libraries. It's compatible with both .NET 3.5+ Web and Windows applications.
How about Scryber? It allows PDF report templates to be defined using xml and bound to data within your application at run time. http://scryber.codeplex.com/
To elaborate on Ray Burns answer, if you are looking for an implementation example, see:
Custom Data Grid Document Paginator
Which is a great starting point.
I've reccently accomplished task of developing own reporting system, which basically consist on design enviroment and data Source manager. The first task was to develop WYSWIG-like design enviroment. I've done this using GDI+, without even bothering about printing, as it came out printing/generating print preview was easiest than i expected, In general it only takes to draw all things on screen to graphics object of printing event.
I think that in case of WPF it would be similar, so all you should worry about is to display you report on screen and printing would be only few lines of code.
Without getting into a whole political discussion about the future of WPF, the best option we found was to wrap the ReportViewer in a Windows Forms host control.
http://blog.pineywoodstech.com/index.php/2012/01/using-microsoft-reportviewer-with-wpf/

Resources