How to hide a control if the underlying DataContext is null?
This approach is easier:
<CheckBox Visibility="{Binding Path=checkedField, TargetNullValue=Collapsed }">
When the bound property checkedField
is null, the Visibility will be set to Collapsed.
Have a converter like follows,
public sealed class NullToVisibilityConverter : IValueConverter{ public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value == null ? Visibility.Hidden: Visibility.Visible; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); }}
Now, bind the property with the Visibility property as well. Like,
<ListBox ItemsSource="{Binding Path=Squad}" Visibility="{Binding Converter={StaticResource nullToVisibilityConverter}, Path=Squad}"> <ListBox.ItemTemplate> <DataTemplate> <CheckBox Content="{Binding}" /> </DataTemplate> </ListBox.ItemTemplate></ListBox>
I also needed this for a WindowsPhone WinRT app. I ended up using @PrinceAshitaka's converter with a minor modification in the binding as suggested in this answer to a similar question
You should use FallbackValue=Collapsed
to avoid showing the control precisely when the datacontext is null. Not sure why TargetNullValue=Collapsed
didn't work for me.
Visibility="{Binding Converter={StaticResource NullToVisibilityConverter}, FallbackValue=Collapsed}"