Saturday, March 4, 2017

WPF Tip #1 - IsAsync and WPF Bindings

Welcome to a new series of quick tips for .NET desktop developers using WPF. Expect new tips (at least) weekly on this site. For links to other great resources for .NET developers, please check out my daily link blog, the Morning Dew.

IsAsync

The IsAsync attribute on a WPF data binding allows your UI thread to remain responsive to user activity while the property to which a control is bound is retrieving data. This can be useful if the application must fetch large amounts of data or when a slower database or web data source is invoked.

Here's a sample usage of the attribute on a simple ListView. This ListView gets a list of items from a user's media catalog and presents them in a simple grid format with headers.

<ListView HorizontalAlignment="Left" Margin="10" VerticalAlignment="Top" ItemsSource="{Binding Path=MediaCatalog, IsAsync=True}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Artist" DisplayMemberBinding="{Binding Path=Artist}" Width="80"/>
            <GridViewColumn Header="Title" DisplayMemberBinding="{Binding Path=Title}" Width="100"/>
            <GridViewColumn Header="Category" DisplayMemberBinding="{Binding Path=Category}" Width="80"/>
            <GridViewColumn Header="Purchase Date" DisplayMemberBinding="{Binding Path=PurchaseDate}"/>
            <GridViewColumn Header="Number of Views" DisplayMemberBinding="{Binding Path=NumberOfViews}"/>
            <GridViewColumn Header="Year" DisplayMemberBinding="{Binding Path=Year}"/>
        </GridView>
    </ListView.View>
</ListView>

While the data is being retrieved by the MediaCatalog's getter, a FallbackValue can be specified. In this case, a data row with a Title of "Loading…" could be used to indicate to the application's user that live data is on its way.

More information on WPF data binding on MSDN.

2 comments:

  1. Does the IsAsync-ness cascade to child bindings? For example, your main ListView ItemsSource binding to MediaCatalog is async, but you have sub-bindings to Artist, Title, etc. that aren't marked as IsAsync=True. Will those sub-bindings still be a bottleneck?

    ReplyDelete
    Replies
    1. It depends. If the child item's data is changing at a point where the collection is not changing, then there could be a bottleneck there. If the items in the collection only update their properties when the collection is changing (or any properties of the individual properties update very quickly), then this method will be fine. Otherwise, you might want to consider adding IsAsync to the other props.

      Delete

Note: Only a member of this blog may post a comment.