1

我正在尝试学习如何使用 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}}"
4

1 回答 1

12

...当它试图解释RequiredFieldConverterIValueConverter. 您需要使用StaticResourceorDynamicResource来引用转换器,就像您在第二个示例中所做的那样。

<TextBox Text="{Binding ElementName=textBox2, Path=Text, Converter={StaticResouce RequiredFieldConverter}}" Name="textBox3" Width="120" />
于 2012-04-16T23:09:57.360 回答