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.
This question intends to provide a list of solutions to common pitfalls, "gotcha's", or design issues when developing WPF applications. This can also include proper design-patterns as long as there is an explanation as to why it works best. Responses should be voted up or down based on how common the type of issue is. Here are the rules:
One response per post. This will clearly give the most common issues the highest ranking.
It would be best to provide the link to the a related post or solution already living somewhere in SO land.
Problem : The major issue I have seen so far is that people start coding in WPF with the winform UI model in mind.
Solution: WPF is not WinForms/MFC/Win32 So Forget all the UI side assumptions and norms you have used and learned while developing Windows based UI for last 20+ years.
It is very important to understand the core ideas behind this platform, This link- Major UI Development Breakthroughs in the new WPF platform will give an in depth view of WPF. Which lists out the following points. The highlighted ones are my favorite features of this platform.
Advanced Graphics
Drawing Object Model
Rich Application Text
Adaptable UI Layout
Flexible Content Model
Lookless Controls
Data-Driven UI
Consistent Styles
Triggers
Declarative Programming
Not realising how bad the font rendering is at the start of a project and being told by the client they can't stand looking at it because of how fuzzy everything looks.
Problem: Using the M-V-VM design pattern, where do I instantiate the views? Does this happen in the ViewModel? SO Question 1, SO Question 2
Solution: WPF development is most effective when using the M-V-VM pattern as opposed to other common patterns such as M-V-C. The tendency is to treat the ViewModel the same as you would the controller which would handle opening and creating views as well as the models. This is not the case in M-V-VM. Views are the only place where are the views should be created. The ViewModels should know nothing of the view. SO Answer 1, SO Answer 2
Problem/Question: SO Question
How do I expose a DependencyProperty
of a component in my user
control to users? There are plenty
of examples of how to expose a normal
property by creating a new dependency
property and binding, but none on how
to expose a read-only property like
FrameworkElement.ActualWidthProperty.
Solution: You need to expose a new Readonly DependencyProperty in your user control, and update it whenever your contained "component"'s ActualWidthProperty gets updated. This requires using DependecyPropertyDescriptor to get notified of changes that occur. SO Solution
Getting data binding to work properly between properties defined in ContentControls (Windows, UserControls, etc..) and properties on elements that make up the controls content. For example. Let's say I have a Window that looks like this:
<Window x:Name="MyWindow"....>
<TextBlock Text="{Binding Path=PropertyDefinedInMyWindow}" />
</Window>
Problem: No matter how often you update the "PropertyDefinedInMyWindow" it never gets reflected in the TextBlock. SO Question
Solution: You need to set the DataContext of the Window or tell the binding which element the property lives on. SO Solution
Ivan Towlson did a really good presentation on this topic. Most of the information is in his slides, which you can get from here:
http://hestia.typepad.com/flatlander/2008/08/codecamp-2008-.html
Using code - behind in views, which makes baby FSM cry.
Related
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 11 years ago.
I learning WPF MVVM pattern for couple of weeks already.
I still don't have clear understanding of this pattern.
I've read this topic https://stackoverflow.com/questions/275098/what-applications-could-i-study-to-understand-datamodel-view-viewmodel and almost all referenced articles.
The problem with all examples is that they have "a lot of extra stuff" (menus, several views etc. etc.) It's good when you need to learn how to do complex things, but it is not good when you looking for something you can start with.
I would like to have an application which I can use as skeleton to build my own application. I.e. I would like to see an application which has only absolutely mandatory things, that would be I suppose:
Main window
Model class
ViewModel class
View class
some ICommand implementation? (am I need something like that)?
probably I'm missing something
Part of the problem is, if you think about it, most of these aren't anything specific.
If you want only the "pure requirements", pretty much the only thing you'll need is some ICommand implementation. This is because the following are just standard WPF or C# classes:
Main Window -> Just use a Window
Model class -> This is your normal project data. Shouldn't be changed for MVVM
ViewModel class -> This is just a normal C# class that implements INotifyPropertyChanged
View class -> Standard WPF UserControl
The only thing you kind of need is an ICommand implementation that routes delegates to an ICommand. This can be ripped out of any MVVM framework (they all have at least one, but usually two implementations, one for Action and one for Action<T>, where the argument is routed from CommandParameter).
If you need a simple implementation of the command, you're welcome to steal the one from the code of my MVVM Series. The code for it isn't trying to be a "framework", since the goal was to show just the basics of MVVM.
Check out this video by Jason Dollinger on MVVM. It's a small example that goes through the process of creating a non-ideal implementation, and then how to do it properly using MVVM. I found it very useful when starting out on MVVM. I thought the video was solid enough that I didn't even need to look at the source, but that is available as well.
look at this cool toolkit
MVVM Light Toolkit
http://www.galasoft.ch/mvvm/
I wrote a very basic MVVM example here if you're interested.
When I first started learning MVVM I had the same problem you did... I couldn't find any simple resources to explain the very basics of MVVM. It was even harder when I was trying to explain the MVVM design pattern to someone else, so this was a sample app I put together for him. I thought it was fairly simple and straightforward, so posted it online.
Edit: The actual "MVVM skeleton" I usually use looks more like the code found in this link. The first link was an extremely mvvm simple app with a single page, however the 2nd one starts with an AppViewModel which can handle switching Views.
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 just want to raise this question about WPF's User Control. I just started using this 'control' in my WPF applications, instead of 'adding' all my controls in one WPF window.
Anyways, would I get a faster process time if I use User Control? How about Dependency Properties? Can I still 'communicate' between my User Control and my WPF window?
What are your thoughts about it? Thanks in advance.
UserControls should be used for reuse, but this is not the main reason to use them.
the main reason to use useControsl is to seperate different parts of your xaml, so that each part is in charge of one responsibility only. for example, if you would write VisualStudio, you would create the ToolBox in one userControl, the CodeEditor in another userControl, etc. this is mainly for SRP, or Single Responsibility Priniciple.
Reuse, or DRY (Don't Repeat Yourself) is important, but SRP is WAY more important.
As to communication - yes, you would use dependecy properties.
The main reason to use UserControls is to bundle a set of controls so they can be reused (normally within the same application)
As for 'performance' you are adding an extra node to the visual tree so it would be slower but that will be hardly noticeable.
Communication between a UserControl and the window (or its parent) is completely similar to any other control you add to a layout class.
I only use UserControl when it's need to share group of controls between two or more places. To communicate between UserControl and Window you should implement DependencyProperty -ies in your user control. It's disadvantage. So, when it's possible I avoid using UserControl and use it only, for instance, to share layout between two versions (WPF and XBAP).
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Okay, to give a little background, I learned WPF about 3 years ago and have kept reasonably up to date with what's happened since in various different versions. I looked at (and implemented) MVVM on a couple of projects, had a good look at frameworks like Prism so I think I'm pretty well versed in most areas of the framework. I've also worked briefly on a couple of small Silverlight 2.0 projects.
My problem is this, I'm about to start a Silverlight job at a new company and while I'm very comfortable that I can do the job well, I feel like my WPF knowledge may cause me some issues. I've gone over the WPF/Silverlight guidance white-paper on codeplex which is excellent and really helpful but although it highlights the differences that still leaves me wondering how to get around those differences.
For example, I know that DataTriggers are missing as areMultiBindings and a whole array of other stuff. What I'm interested in reading about is not the differences per se but how you get aronud those differences or what other patterns are useful in Silverlight. What if I need a DataTrigger? clearly my design should take these things into account.
So, the question is,..if you've gone through this transition, what differences caused you the most trouble and how did you get around it?
First, while this is dated to Silverlight 3, this white paper goes through the differences between WPF and Silverlight in detail:
Microsoft WPF-Silverlight Differences White Paper
http://wpfslguidance.codeplex.com/releases/view/30311
That is a great first step to familiarize yourself with the differences.
You might also want to take a look at the Prism project. One of the goals of this project is to build a set of interoperable functionality between Silverlight and WPF so you can essentially build enterprise applications that target both platforms and reuse the majority of code. Familiarizing yourself with the project will help highlight differences as well:
http://compositewpf.codeplex.com/
Finally, while Silverlight might not have data triggers, you can use a combination of features such as behaviors and triggers:
http://www.silverlightshow.net/items/Behaviors-and-Triggers-in-Silverlight-3.aspx
And the Visual State Manager (VSM):
http://timheuer.com/blog/archive/2008/06/04/silverlight-introduces-visual-state-manager-vsm.aspx
To accomplish most of what you need.
Giving a Silverlight port per se for our WPF App, the following are the two 'pain' points we encountered.
Splitting up and grouping XAML's/modules for improved performance and on demand XAP downloading using MEF.
Challenge of achieving Binary Compatibility using the same code base for WPF/Silverlight.
A few of our Functionality required OOB and user acceptance.
We optimized a bit of Functionality relying on IsolatedStorage.
Hope this helps.
[ Now that Silverlight 4.0 has a stable build, we had a few Visual Studio hiccups over the last few releases which resolved itself overtime. (We stuck to Silverlight 3.0 and somewhere in mid march jumped to SL 4.0 beta and final release)].
N.B. : I have tried to keep things way abstract to not reveal the identity of the client.
MarkupExtension
IMultiValueConverter
Template.Triggers
Style.Triggers
Binding RelativeSource={RelativeSource AncestorType...
Binding.IsAsync
{x:Static ...
{DynamicResource...
Grid.IsSharedSizeScope / SharedSizeGroup
All of these are not supported in Silverlight and you have to workaround them.
Every case needs it's own judgment about how to "fill the gaps"
For the triggers part, the only solution is to use VisualStateManger.
The following article gives a good example of how to make the transition from triggers to VSM: http://blogs.msdn.com/b/wpfsdk/archive/2009/02/27/the-visualstatemanager-and-triggers.aspx
Next, OnApplyTemplate is fired in different order, which might affect any Custom Controls or UserControls you might have created.
WPF:
UserControl Constructor
MyControl Constructor
MyControl.OnApplyTemplate
UserControl Loaded
MyControl Loaded
Silverlight:
UserControl Constructor
MyControl Constructor
MyControl Loaded
UserControl Loaded
MyControl.OnApplyTemplate
And of course Microsoft has an article about that, called "WPF Compatibility" and gives a more thorough overview about the differences and changes between WPF and Silverlight:
http://msdn.microsoft.com/en-us/library/cc903925(VS.95).aspx
Hope this helps
Silverlight forces you to make some changes to your design patterns, which, if is pervasive throughout your software, can render code reuse quite moot.
For instance, data template selectors are missing -- I found this to be quite a shock.
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.
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.
What are the top 3 main concepts in WPF that you need to understand in order to write good WPF code?
I think the most important aspects of WPF concepts are:
Templates and Styles (the way you define the behaviour and appearance of your application)
Data Binding (the way you should glue together your UI with your business objects
Declarative UI definition through XAML
Maybe there are other elements but in my opinion those are fundamental for WPF thinking.
I would say the single most important concept is the UI pattern Model-View-ViewModel, or as I like to call Model-View-ModelController. This is crucial to building apps successfully in WPF. Besides that, the real conerstones are Databinding, Templating, and Styles as others have mentioned. There is a nice post here on some common pitfalls to avoid when developing in wpf.
The real basics that you have to grok is:
XAML
Layout
Content model
Data binding
Their are loads more but these are the ones that has changed the most from winforms...
Also check out this thread: Interview questions: WPF Developer
I duno about top 3 but Attached/Dependency properties is pretty important.
I can only think of two big main concepts in WPF
In no particular order:
Bindings
Templating and Styles
When you have learned those two concepts, you will be able to write decent WPF code...
Oh, and the third would be XAML.. but that is the language... however, you might want to try to put as little in the code behind and as much in your XAML file...
Its quite easy to choose the code behind approach, but try to do it in XAML in stead...
The most concept in WPF lies on the stype and the behavior of the UI. It has lot of features, among them the following three are the most useful and important aspect.
Building the data binding of the business object and UI.
Changing style and more user friendly as to easy implement in UI so that the look and fill is good as user perspective.
Redefining the UI through the XAML and changing the font, style, implementing animation etc.
So its most powerful concept.
To know more about the technology, one should know about the architecture of a technology. However following are the basic but most important concepts in WPF are -
1) XAML
2) Rich Layout, Panels and Windows
3) Content model
4) Data binding