Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

wpf

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!

like image 902
Boris Avatar asked Apr 07 '11 11:04

Boris


2 Answers

Try referencing your converter as a StaticResource

<TextBlock Visibility="{Binding Path=UrlAddress, Converter={StaticResource visibilityConverter}}"> 
like image 176
Brian Ingenito Avatar answered Nov 09 '22 05:11

Brian Ingenito


forgot to mention Binding Markup Extension with ElementName attribute maybe?

<TextBlock Visibility="{Binding ElementName=XXX, Path=UrlAddress, Converter={StaticResource visibilityConverter}}">  `
like image 45
Bek Raupov Avatar answered Nov 09 '22 05:11

Bek Raupov