【发布时间】:2013-04-18 21:12:25
【问题描述】:
我在窗口中有一个 TextBox,我使用以下简单的转换器将其绑定到一个值:
public class TestConverter : MarkupExtension, IValueConverter {
public override object ProvideValue(IServiceProvider serviceProvider) {
return this;
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
return "x";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
return "y";
}
}
绑定本身如下所示:
Binding bnd = new Binding(nm); // 'nm' is a string with the binding path which is just
// a property name of the future source object
bnd.Converter = new TestConverter();
bnd.Mode = BindingMode.OneWayToSource;
oj.Fe.SetBinding(TextBox.TextProperty, bnd); // <--- Exception occurs here
如果我移除转换器或将模式设置为 TwoWay,则不会引发异常。为什么会引发异常,我该如何解决或至少解决该问题?
编辑: 在这种情况下,似乎必须在绑定之前提供数据上下文,以免引发异常。为什么会这样?
【问题讨论】:
-
有什么异常?您提供了很多数据,但忽略了最重要的数据。
-
System.Windows.Data.BindingExpression.IsValidValueForUpdate 中的 NullReferenceException(对象值,类型 sourceType)
-
你正在绑定
OneWayToSource,但我没有看到你提供要绑定的源属性,你想将TextBox.TextProperty绑定到什么,你必须将它绑定到某个东西跨度> -
源属性由字符串变量
nm指定。为文本框提供的数据上下文具有nm属性(实际上,提供的数据上下文是DynamicObject和INotifyPropertyChanged)。请注意,文本框在绑定时没有数据上下文。 -
Heh.. 当我在绑定之前为其提供数据上下文时,异常消失了。
标签: wpf data-binding converter