在我看来,ConvertBack
方法用于将数据的视觉呈现转换为特定的 DataType。
例如:您使用转换器将布尔值true
转换为字符串"TrueBoolean"
。此文本将显示在您的 TextBox 中。当您更改 TextBox 的值时,绑定再次触发时(默认为 OnFocusLost),ConvertBack
方法将被调用。现在,您的 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));
}
}
如果我没记错的话,这种技术在数据表格中经常使用。
希望这样比较清晰明了...
更新
关于你在评论中提出的问题:
要覆盖默认的OnFocusLost
绑定行为,你需要像这样更改你的绑定:
<TextBox Text="{Binding MyText, UpdateSourceTrigger=PropertyChanged}"/>
<!--syntax might differ, can't access VS at the moment.-->
INotifyPropertyChanged
接口。对于大多数控件来说,默认情况下都是双向绑定(你可以检查控件上的BindsTwoWayByDefault
属性来确认)。这在文本框和复选框等控件中非常重要,因为它们的值可以通过代码或用户输入进行更新。 - RoelF