我正在尝试学习如何使用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}}"
答案 0 :(得分:12)
...在尝试将RequiredFieldConverter
解释为引用到IValueConverter
时,您收到了错误消息。您需要使用StaticResource
或DynamicResource
来引用转换器,就像您在第二个示例中所做的那样。
<TextBox Text="{Binding ElementName=textBox2, Path=Text, Converter={StaticResouce RequiredFieldConverter}}" Name="textBox3" Width="120" />