IMO,ConvertBack 方法用于将数据的可视化表示转换为特定的 DataType。
例如:您使用转换器将布尔值true 转换为字符串"TrueBoolean"。此文本将显示在您的 TextBox 中。当您更改 TextBox 的值时,将在绑定再次触发时立即调用 ConvertBack 方法(默认为 OnFocusLost)。现在您的ConvertBack 方法将尝试将新值转换为您想要的数据类型。因此,您必须实现将"FalseBoolean" 转换为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));
}
}
如果我没记错的话,这种技术在 DataGrids 中被大量使用。
希望这有点清楚......
更新
评论中关于你的问题:
要覆盖默认的 OnFocusLost 绑定行为,您必须像这样更改绑定:
<TextBox Text="{Binding MyText, UpdateSourceTrigger=PropertyChanged}"/>
<!--syntax might differ, can't access VS at the moment.-->