Search code examples
c#wpfsilverlightbindingdatacontext

How to hide a control if the underlying DataContext is null?


I have an object in my view model that has a bunch of properties, some of them will occasionally be null. I don't want to just show some controls if these particular controls are null. How would I go about hiding the control if the bind is null? I was thinking of some sort of converter, but don't know how I'd go about doing it exactly. Any ideas?

edit: sorry, I should mention that this will also be in Silverlight, so I'm not sure if Style triggers would work...?


Solution

  • 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>