December 18, 2014

Typical Traps In WPF

In WPF, few traps are present where developers required lots of time to resolve issues. In this post I'm going to list down the common errors arise in development and their solution so that developer would resolve them quickly.

1. Layout Section


Q1. Scrollbar is not active or visible
Ans. If your control is within a vertical stackpanel, it gives the control infinite height to layout. Consider replacing the stackpanel by a dockpanel.

Q2. I created a data template and set HorizontalAlignment to Stretch but the item is not stretched
Ans. Set the HorizontalContentAlignment on the list to Stretch.

2. DataBinding


Q1. I changed a value, but the binding is not reflecting my changes
Ans. Check the following conditions:
         a. Check the output window in VisualStudio, if there are any binding errors.
         b. Does your data support INotifyPropertyChanged?
         c. Just firing a PropertyChanged event without changing the data does not work. Because the binding checks if oldvalue != newvalue

3. Performance


Q1. My list of items takes too long to render
Ans. Your list is not virtualized. This means, all items will be generated, even if they are not visible. To avoid this check the following points:
         a. ScrollViewer.CanContentScrol must be set to False
         b. Grouping must be disabled
         c. You replaced the ItemsPanel by one that does not support virtualization
         d. You are using a too complex data template.

Q2. Animations cause a high CPU load
Ans. WPF cannot use hardware acceleration and does software rendering. This can be because of the following points:
         a. You have set AllowTransparency to True on your window.
         b. You are using legacy BitmapEffects instead of fast pixel shaders (Effects).
         c. Your graphics adapter or driver does not support DirectX

4. Custom Controls

Q1. I created a custom control, but the template it not showing
Ans. Check the following conditions:
         a. Check if you have overriden the metadata of the DefaultStyleKeyProperty and set it to your type.
         b. Check if your template is surrounded by a style and both have the right TargetType
         c. Check if the resource dictionary that contains the default style is loaded

Q2. I use {TemplateBinding} in my ControlTemplate, but is not working
Ans. Check the following conditions:
         a. In most cases you have to replace {TemplateBinding Property} by {Binding Property RelativeSource={RelativeSource TemplatedParent}}
         b. You can only use TemplateBinding within the content of your control template. It will not work anywhere else!
         c. If you want to access a parent property in the trigger, you have to use a normal binding, with relative source Self.
         d. TemplateBinding works only within the VisualTree of the template. You cannot use it on items that are only in the logical tree. Neighter on Freezables or to do two-way binding.