This code example will show how to hide a listbox from the user when it doesn’t have any items.
It involves binding the Visibility of the listbox to the Items.Count of the listbox. We run the Items.Count through a converter that will return a Visibility.Visible object if the Item.Count is not zero.
Here is the converter class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows;
namespace HideAListBox
{
public class ZeroCollapsedNonZeroVisible : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var rv = Visibility.Visible;
var val = 0;
int.TryParse(value.ToString(), out val);
if (val == 0)
{
rv = Visibility.Collapsed;
}
return rv;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
Here is the window code:
<Window x:Class="HideAListBox.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:converter="clr-namespace:HideAListBox"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<converter:ZeroCollapsedNonZeroVisible x:Key="hideListBox"/>
</Window.Resources>
<DockPanel LastChildFill="True">
<Button Content="Add Item" Click="addItemClick" DockPanel.Dock="Top"/>
<Button Content="Clear Items" Click="clearItemsClick" DockPanel.Dock="Top"/>
<ListBox Margin="3" BorderBrush="Blue" Name="myListBox"
Visibility="{Binding ElementName=myListBox,
Path=Items.Count,
Converter={StaticResource hideListBox}}"/>
</DockPanel>
</Window>
The entire project can be downloaded here.