Search code examples
silverlightwindows-phone-7xamlwindows-store-apps

Show a textblock if an ObservableCollection is Empty


I want to show a textblock that says "you have no data" when a collection that should be shown is empty.

I can easily get this to work on page load by using a converter, but since that doesn't get notified when the collection data changes the code doesn't work:-

TextBlock Visibility="{Binding Devices, Converter={StaticResource EmtpyListToVisibility}, Mode=OneWay}" Text="You have no devices added, please press the Add Device button on the application bar" TextWrapping="Wrap"></TextBlock>

<phone:LongListSelector Margin="0,12,0,0" ItemsSource="{Binding Devices, Mode=OneWay}" ItemTemplate="{StaticResource DeviceTemplate}" LayoutMode="List" VerticalAlignment="Top" >                       
</phone:LongListSelector>

In windows 8 apps I have added a property called xxxHasRecords, then I subscribe to the Observable collections CollectionChanged event and used the property notification so my UI can be updated. I find myself writing this code so often that there just has to be a better way of handling it!

Thanks

Ross


Solution

  • Rather than bind to the ObservableCollection, you should bind to the ObservableCollection.Count property. The collection implements INotifyPropertyChanged, so will notify your bindings whenever its size changes. Your value converter then simply has to check for zero.