【问题标题】:Can't convert Resource to string using TypeConverter无法使用 TypeConverter 将资源转换为字符串
【发布时间】:2009-03-23 13:33:34
【问题描述】:

例外:

无法将属性“文本”中的值转换为类型的对象 '系统.字符串'。无法投射物体 要键入的“MyApp.Foo”类型 '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";
    }
}

怎么了?

【问题讨论】:

    标签: wpf resources typeconverter


    【解决方案1】:

    您不需要在那里使用值转换器而不是类型转换器。

    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();
         }
     }
    

    【讨论】:

    • 这是一个正确的方向。它适用于 Text="{Binding Converter={StaticResource fooConverter}, Source={StaticResource foo}, Mode=OneWay}"
    • 如何在没有 XAML 的情况下获得相同的结果?
    猜你喜欢
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    相关资源
    最近更新 更多