views:

740

answers:

1

Exception:

Cannot convert the value in attribute 'Text' to object of type 'System.String'. Unable to cast object of type 'MyApp.Foo' to type 'System.String'.

XAML:

<Window.Resources>
  <my:Foo x:Key="foo"></my:Foo>
</Window.Resources>

<TextBox Text="{DynamicResource foo}"></TextBox>

C#

[TypeConverter(typeof(FooConverter))]
public class Foo
{
    public Foo()
    {}
}

public class FooConverter : TypeConverter
{
    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        return true;
    }

    public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
    {
        return "Foo";
    }
}

What is wrong?

+3  A: 

Don't you need to use a value converter there instead of a type converter.

XAML

<Window.Resources>  
    <my:Foo x:Key="foo"/>
    <my:FooConverter x:Key="fooConverter />
</Window.Resources>
<TextBox Text="{DynamicResource foo, Converter={DynamicResource fooConverter}}"></TextBox>

C#

public class FooConverter : IValueConverter
{ 
     public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
     {
          return ((Foo)value).ToString();
     }
 }
sipwiz
This was a right direction. It works with Text="{Binding Converter={StaticResource fooConverter}, Source={StaticResource foo}, Mode=OneWay}"
alex2k8