Question

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?

Was it helpful?

Solution

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();
     }
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top