Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

c# - What is the use of ConvertBack method in IValueConverter interface?

What is the use of ConvertBack method in the IValueConverter interface.

When will it be called?

Or what is the order of invocation of the Convert and ConvertBack methods?

I have asked the question here because: I have bound one property of codebehind to TEXTBOX’s TEXT Property and am using convertor for that property. The first Convert Method invokes and when I change TEXT in TEXTBOX nothing happens... but as soon as I close the form the ConvertBack method invokes.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

IMO, the ConvertBack method is used to convert your visual representation of the data to the specific DataType.

For example: you use a Converter to convert a boolean true to the string "TrueBoolean". This text will be displayed in your TextBox. When you change the value of the TextBox, the ConvertBack method will be called as soon as the binding fires again (default OnFocusLost). Now your ConvertBack method will try to convert the new value to the datatype you want it to be. So you will have to implement logic to convert "FalseBoolean" to false.

public class Converter : IValueConverter
{
    object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (bool) value ? "TrueBoolean" : "FalseBoolean";
    }

    object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var s = (string) value;
        if (s.Equals("TrueBoolean",StringComparison.CurrentCultureIgnoreCase))
            return true;
        if (s.Equals("FalseBoolean", StringComparison.CurrentCultureIgnoreCase))
            return false;
        throw new Exception(string.Format("Cannot convert, unknown value {0}", value));
    }
}

This technique is used a lot in DataGrids if I'm not mistaken.

Hope this is a bit clear...

UPDATE
About you question in the comment:
To overwrite the default OnFocusLost binding behavior you have to change your binding like this:

<TextBox Text="{Binding MyText, UpdateSourceTrigger=PropertyChanged}"/>
<!--syntax might differ, can't access VS at the moment.-->

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...