无法使转换器工作

时间:2012-04-16 23:04:29

标签: c# wpf binding ivalueconverter

我正在尝试学习如何使用IValueConverter。我有以下转换器:

[ValueConversion(typeof(string), typeof(string))]
public class RequiredFieldConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
            return "";

        return value.ToString() + "*";
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
            return "";
        var str = value.ToString();
        return str+"Convert Back testing";
    }
}

我在app.xaml文件中添加了RequiredFieldConverter资源,我想尝试将其作为:

<TextBox Name="textBox2"  Width="120" />
<TextBox Text="{Binding ElementName=textBox2, Path=Text, Converter=RequiredFieldConverter}" Name="textBox3" Width="120" />

我希望当我在textbox2中键入“hello”时,它会在textbox3中显示“hello *”,但它不起作用。实际上我在运行时遇到以下异常:

  

{“无法将'System.String'类型的对象强制转换为'System.Windows.Data.IValueConverter'。”}

我也知道值转换器功能正常工作,因为它在我这样做时起作用:

 Content="{Binding Source={StaticResource Cliente}, Converter={StaticResource RequiredFieldConverter}}"

1 个答案:

答案 0 :(得分:12)

...在尝试将RequiredFieldConverter解释为引用IValueConverter时,您收到了错误消息。您需要使用StaticResourceDynamicResource来引用转换器,就像您在第二个示例中所做的那样。

<TextBox Text="{Binding ElementName=textBox2, Path=Text, Converter={StaticResouce RequiredFieldConverter}}" Name="textBox3" Width="120" />
相关问题