Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot make converter work

I am trying to learn how to use IValueConverter. I have the following converter:

[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";
    }
}

I have added the RequiredFieldConverter resource in my app.xaml file and I want to try it as:

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

I was hoping that when I type "hello" in textbox2 it shows "hello*" in textbox3 but it does not work. In fact I get the following exception at runtime:

{"Unable to cast object of type 'System.String' to type 'System.Windows.Data.IValueConverter'."}

also I know that the value converter function is working because it works when I do:

 Content="{Binding Source={StaticResource Cliente}, Converter={StaticResource RequiredFieldConverter}}"
like image 258
Tono Nam Avatar asked Dec 21 '25 05:12

Tono Nam


1 Answers

... You are getting the error as it trying to interpret RequiredFieldConverter as an reference to an IValueConverter. You need to use a StaticResource or DynamicResource to reference the converter as you have done in your second example.

<TextBox Text="{Binding ElementName=textBox2, Path=Text, Converter={StaticResouce RequiredFieldConverter}}" Name="textBox3" Width="120" />
like image 73
Dennis Avatar answered Dec 22 '25 19:12

Dennis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!