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
Answer: 1
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.
Answer: 2
In this case i use a BooleanToVisibilityConverter
public class BooleanToVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { bool invert = false; if (parameter != null ) { invert = System.Convert.ToBoolean(parameter); } bool isVisible = System.Convert.ToBoolean(value); if (invert) { isVisible = !isVisible; } return isVisible ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { Visibility result = (Visibility) Enum.Parse(typeof(Visibility), value.ToString(), true); return result == Visibility.Visible ? true : false; } }
and change the binding of the Visibility-Property of the TextBox to the following
<TextBlock Visibility="{Binding Devices.Count, Converter={StaticResource boolToVisibilityConverter}, Mode=OneWay}" Text="You have no devices added, please press the Add Device button on the application bar" TextWrapping="Wrap"> </TextBlock>
When the Collection is empty Count returns the value 0. The Converter uses System.Convert.ToBoolean which converts 0 to false and all other values to true.
False is returned as Visibility.Collapsed and True as Visibility.Visible.
by : Jehofhttp://stackoverflow.com/users/83039
No comments:
Post a Comment
Send us your comment related to the topic mentioned on the blog