Wednesday, April 26, 2017

WPF Tip #9 - ObservableCollection and the CollectionChanged Event

Tip #9 will examine something that seems like it should work according to the documentation on MSDN, but I have seen it not work as expected.

When using ObservableCollection<T>, if some code in your application needs to react when items are added or removed from the collection the CollectionChanged event can be handled.

private ObservableCollection<Pill> _pills = new ObservableCollection<Pill>();

public MainWindow()
{
    InitializeComponent();
    Pills.CollectionChanged += Pills_CollectionChanged;
}

public ObservableCollection<Pill> Pills
{
    get { return _pills; }
    set { _pills = value; }
}

void Pills_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
    // Pills Collection Changed - do something
}

The issue I have encountered with this code is that setting that value of the Pills property directly does not always fire the CollectionChanged event.

Pills = someOtherPillCollection;

What I did to work around this was to remove the property setter and only work with the collection through its properties. In this case, by using Clear() and Concat<T>().

Pills.Clear();
Pills.Concat<Pill>(someOtherPillCollection);

ObservableCollection does not have an AddRange() method. You could write your own extension method to do it, but I prefer to use the LINQ extension method Concat<T>().

Has anyone else seen this same issue?

 

del.icio.us Tags: ,

Thursday, April 6, 2017

WPF Tip #8 - Grids and Rendering Performance

Today's tip is a quick one. It's about choosing the best panel for the layout of the UIElements in your WPF Window or Control.

Many developers will default to putting everything into a Grid. It's easy. They're flexible and offer many layout options. When a Window is relatively simple and performance is not being analyzed by users or stakeholders, using Grids everywhere might be ok. However, professional WPF developers should make it a practice to learn the differences in features and performance of each panel and choose the best one for a particular layout scenario.

In general, you should first try a StackPanel. If you can accurately lay out your Window with StackPanels without a deep nested web of them, they are the best way to go. They are much faster than Grids in both measurement of elements and layout/arrangement.

There are several other panels included in WPF. These are the most common, ranked from fastest to slowest (in general):

  1. Canvas
  2. StackPanel
  3. WrapPanel
  4. DockPanel
  5. Grid

This ranking is based on the accepted answer in this StackOverflow question. If you're interested in reading more about each of the panels and how they 'stack' up in different scenarios, I highly recommend reading the question and top answer.

Cheers!

 

del.icio.us Tags: ,