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.

No comments:

Post a Comment