Andrew Arnott
Andrew Arnott

Reputation: 81801

How to data bind based on emptiness of a collection?

I want to make a TextBlock visible only when a collection is empty. I have a ListView that is data-bound to the collection already and that's simple. I just want to display something else when the ListView is otherwise empty.

I wrote an IValueConverter that would take the collection, or count, or whatever I need, and return a Visibility appropriately. The XAML looks like this:

<TextBlock Visibility="{Binding Count, ElementName=ContactsList, Converter={StaticResource visibilityWhenEmpty}}"
           Text="No contacts yet.  Add one using the AppBar below." />

The trouble is that binding just the collection itself only calls my value converter once, when it's empty, and not again when the contents of the collection changes (kinda makes sense). And when, as shown above, I try binding against the collection's Count property, it doesn't call my value converter at all.

Any ideas?

Upvotes: 0

Views: 267

Answers (2)

D J
D J

Reputation: 7028

I have faced the same issue. I applied a tricky solution. It might work for you as well. Taks a temporary combo box and bind the collection with that.

<ComboBox  x:Name="TempComboBox" 
                       ItemsSource="{Binding DataContext.ContactsList,
                                   RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=UserControl}}" >
                <ComboBox.Template>
                    <ControlTemplate>
                        <!--Add file button..-->
                        <TextBlock Content="Your text..."
                                >
                            <TextBlock.Visibility>
                                <Binding Path="Items.Count"
                                         RelativeSource="{RelativeSource Mode=FindAncestor,AncestorType=ComboBox}"
                                Converter="{StaticResource visibilityWhenEmpty}">
                                </Binding>
                            </TextBlock.Visibility>
                        </TextBlock>
                    </ControlTemplate>
                </ComboBox.Template>
            </ComboBox>

Upvotes: 1

Asad
Asad

Reputation: 1

You could use notifyPropertyChanged for Count, or implement using BindableBase.

Upvotes: 0

Related Questions