wpf

WPF: Cannot set the converter - error when starting the app


I want to set the TextBlock to visible/collapsed mode depending on the binded value. It doesn't work and I get this message when I want to debug my app:

Set property 'System.Windows.Data.Binding.Converter' threw an exception.

The value that gets binded is of type Uri. There is an inner InvalidCastException that says:

Unable to cast object of type 'System.String' to type 'System.Windows.Data.IValueConverter'.

Here's my converter:

public class VisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, 
        object parameter, CultureInfo culture)
    {
        if (value is string && string.IsNullOrEmpty(value as string))
        {
            return Visibility.Collapsed;
        }
        else if (value == null)
        {
            return Visibility.Collapsed;
        }
        else
        {
            return Visibility.Visible;
        }
    }

    public object ConvertBack(object value, Type targetType, 
        object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

And here's the XAML that throws the exception:

...
<Page.Resources>
    <converters:VisibilityConverter x:Key="visibilityConverter" />
</Page.Resources>
...
<TextBlock Visibility="{Path=UrlAddress, Converter=visibilityConverter}">
    This never works!
</TextBlock>
...

Help, please!


Solution

  • Try referencing your converter as a StaticResource

    <TextBlock Visibility="{Binding Path=UrlAddress, Converter={StaticResource visibilityConverter}}">