Sylvain B.
Sylvain B.

Reputation: 739

How to display "loading" gif instead of wpf controler when loading?

Consider a TextBlock in wpf that is bound asynchronously to a property in the viewmodel where the get uses a time consuming method. Using the Fallback tag in the xaml code, I can set the Text tag of the TextBlock to "Loading...".

But I have actually a ListBox that is bound to an IEnumerable<MyType> where the List box items display different fields of MyType. How can I have a laoding gif (or any kind of different wpf element) displayed while the bounded IEnumerable<MyType> is being loaded ?

I guess that I could bind the Visibility of the Loading element to some kind of a bool that describes the state of the asynchronous property, but I don't find such a bool in xaml. If it does not exists in xaml, I could work out the state of the loading method and create this bool in the viewmodel. Would that be the best way to achieve it ?

Upvotes: 0

Views: 613

Answers (2)

mm8
mm8

Reputation: 169210

You should read @Stephen Cleary's article about patterns for asynchronous MVVM applications: https://msdn.microsoft.com/en-us/magazine/dn605875.aspx.

You could bind to a NotifyTaskCompletion<IEnumerable<MyType>> source property and use a DataTrigger or a simple binding to the IsNotCompleted property to display an Image until the Result property has been set:

<!-- Busy indicator -->
<Image Source="pic.png" Visibility="{Binding YourItemsSourceProperty.IsNotCompleted,
            Converter={StaticResource BooleanToVisibilityConverter}}"/>
<!-- Results -->
<ItemsControl ItemsSource="{Binding YourItemsSourceProperty.Result}" Visibility="{Binding
          UrlByteCount.IsSuccessfullyCompleted, Converter={StaticResource BooleanToVisibilityConverter}}"/>

Please read the article for more information about do's and don'ts.

Upvotes: 1

grek40
grek40

Reputation: 13448

Depending on the state of ItemsSource, you could change the ControlTemplate:

<ListBox ItemsSource="{Binding Items}">
    <ListBox.Style>
        <Style TargetType="ListBox">
            <Style.Triggers>
                <Trigger Property="ItemsSource" Value="{x:Null}">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="ListBox">
                                <Image Source="LoadingImage.png"/>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Trigger>
            </Style.Triggers>
        </Style>
    </ListBox.Style>
</ListBox>

Upvotes: 2

Related Questions