Trouble Implementing Custom IValueConverter for XAML Binding in WPF - 'InvalidCastException' at Runtime
This might be a silly question, but I'm stuck on something that should probably be simple... I'm trying to implement a custom `IValueConverter` in my WPF application to convert a boolean value to a visibility state for UI elements. However, I am running into an `InvalidCastException` when the converter is called during data binding. Here's the converter code I created: ```csharp public class BooleanToVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is bool boolValue) { return boolValue ? Visibility.Visible : Visibility.Collapsed; } return Visibility.Collapsed; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (value is Visibility visibility) { return visibility == Visibility.Visible; } return false; } } ``` I am using this converter in my XAML as follows: ```xml <Window.Resources> <local:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" /> </Window.Resources> <CheckBox IsChecked="{Binding IsFeatureEnabled}" Content="Toggle Feature" /> <TextBlock Visibility="{Binding IsFeatureEnabled, Converter={StaticResource BooleanToVisibilityConverter}}" Text="Feature is enabled" /> ``` The binding on the `TextBlock` throws an `InvalidCastException` when `IsFeatureEnabled` is set to `null` or not a boolean. I tried handling the null case in the `Convert` method, but it doesn't seem to resolve the issue. As a workaround, I added a fallback boolean property in my ViewModel, but I'd prefer a cleaner solution. Is there a proper way to handle this scenario in the `IValueConverter` so that it does not throw an exception when the bound property is null or of an unexpected type? I am using .NET 5.0 for this application. This is part of a larger CLI tool I'm building. Has anyone else encountered this?