我在一个窗口中有一个 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,则不会引发异常。为什么会引发异常,我该如何解决或至少解决该问题?
编辑:似乎必须在绑定之前在这种情况下提供数据上下文,以免引发异常。为什么会这样?