I have a ListBox that can have multiple items selected at once. I have a UserControl that needs needs to be visible if exactly one item in the ListBox is selected.
Here is the pane that needs to be hidden:
<views:WebMethodsPane x:Name="WebMethodsPane" Grid.Column="1" Grid.Row="0" Margin="5,5,5,0"
Visibility="{Binding SelectedList, Converter={StaticResource SelectionToVisibilityConverter}}" />
The SelectedList object is an ObservableCollection that is filled with items that are selected by the user in the ListBox. (I used a behavior to do this.)
The SelectionToVisibilityConverter goes as follows:
public class SelectionToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var selectedServices = value as ObservableCollection<WebService>;
return (selectedServices.Count == 1 ? Visibility.Visible : Visibility.Collapsed);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
When I run the app, the pane is hidden and stays hidden. The visibility is not being updated when I select different numbers of items from the ListBox. How can I make sure the Visibility updates? Maybe I need to use INotifyPropertyChanged, but I don’t know exactly how to.
The approach I would take would be to add a new property to the bound object, a
SingleItemSelectedboolean property.Something along the lines of:-
So now what you need is a simple
BoolToVisibilityConverter, there are plenty of examples of such a thing, I prefer my own here.Then you xaml (assuming you placed an instance of the converter in the resources with the key “BtoV”):