Ton*_*Nam 1 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";
}
}
Run Code Online (Sandbox Code Playgroud)
我在app.xaml文件中添加了RequiredFieldConverter资源,我想尝试将其作为:
<TextBox Name="textBox2" Width="120" />
<TextBox Text="{Binding ElementName=textBox2, Path=Text, Converter=RequiredFieldConverter}" Name="textBox3" Width="120" />
Run Code Online (Sandbox Code Playgroud)
我希望当我在textbox2中键入"hello"时,它会在textbox3中显示"hello*",但它不起作用.实际上我在运行时遇到以下异常:
{"无法将'System.String'类型的对象强制转换为'System.Windows.Data.IValueConverter'."}
我也知道值转换器功能正在工作,因为它可以在我这样做时工作:
Content="{Binding Source={StaticResource Cliente}, Converter={StaticResource RequiredFieldConverter}}"
Run Code Online (Sandbox Code Playgroud)
Den*_*nis 12
...在尝试将其解释RequiredFieldConverter为对a的引用时,您收到错误IValueConverter.您需要像在第二个示例中那样使用StaticResource或DynamicResource引用转换器.
<TextBox Text="{Binding ElementName=textBox2, Path=Text, Converter={StaticResouce RequiredFieldConverter}}" Name="textBox3" Width="120" />
Run Code Online (Sandbox Code Playgroud)