0
votes

could anyone explain IvalueConverter interface and its method of convert() and convertback() and specially their arguments :object value, Type targetType, object parameter, string language code snippet:

<StackPanel Margin="30">

    <TextBox Name="txtbox"/>
    <TextBox Text="{Binding ElementName=txtbox,Path=Text,Converter={StaticResource RC_converter}}" FontSize="14" />

</StackPanel>



public object Convert(object value, Type targetType, object parameter, string language)
{
    double pkr;
    double dollar = 0.0;
    if (double.TryParse(value.ToString(), out pkr))
    {
        dollar = pkr * 0.0099;
    }
    return dollar;
}

Secondly as above method gives me currency in dollar if I enter rupee amount in the text boxes. So what if I change the amount of dollar from second textbox? Do I need to use convertback for that purpose?

1

1 Answers

0
votes

First you can turn to MSDN for explanation on the arguments. They are explained in details in the Remarks section.

For your usage, you only need to use the first argument in your Convert method- which is the amount of rupees- and multiplied by a fixed ratio, and returns the amount of dollars.

The second question: I should say this is an interesting one.

You are right, if you implement the convertback then everything will almost work.

<TextBox Name="txtbox1" />
<TextBox Name="txtbox2" Text="{Binding ElementName=txtbox1,Path=Text, Mode=TwoWay, Converter={StaticResource RC_converter}, UpdateSourceTrigger=PropertyChanged}" />

You need to do add Mode=TwoWay so ConvertBack will be called, and UpdateSourceTrigger=PropertyChanged so when you type on the Dollar (2nd) textbox, the Ruppe textbox is updated-otherwise it is only updated when Dollar textbox loses focus.

Important:

I said it will almost work because two textboxes binding to each other is a weird circular chain. You input amount of Rupees and the amount of Dollars is updated, which updates the amount of Rupees. You will see the issue.

b = a * 0.0099; //Convert
a = b * 100;    //ConvertBack?????  
b = a * 0.0099; //Convert is called again... and... too bad

So the correct way, is let both textboxes binding to a property in ViewModel, again, two-way binding, and implement convertback method, and specify UpdateSourceTrigger=PropertyChanged.

Here is a similar question, but it is for WPF, just for your reference.