(WPF) 将 OneWayToSource 与转换器绑定会导致立即异常

Kag*_*nar 5 data-binding wpf converter

我在一个窗口中有一个 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";
    }
}
Run Code Online (Sandbox Code Playgroud)

绑定本身表现如下:

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
Run Code Online (Sandbox Code Playgroud)

如果我移除转换器或将模式设置为 TwoWay,则不会引发异常。为什么会以其他方式引发异常,我该如何解决或至少解决该问题?

编辑:在绑定之前,似乎必须在这种情况下提供数据上下文,以免引发异常。为什么会这样?

Ben*_*lde 5

我相信您收到该错误是因为您将 TextBox.TextProperty 绑定到 nm,但 TextBox.TextProperty 为空。对于双向绑定,它必须首先将值从 nm 发送到 TextBox.TextProperty,将其设置为“x”,以便在尝试以其他方式绑定回时不再为 null。删除转换器可能还会删除发现 TextBox.TextProperty 为 null 并产生异常的检查。

因此,如果您要添加以下行:

oj.Fe.Text = "something";
Run Code Online (Sandbox Code Playgroud)

或者甚至可能:

oj.Fe.Text = string.Empty;
Run Code Online (Sandbox Code Playgroud)

oj.Fe.SetBinding(TextBox.TextProperty, bnd);
Run Code Online (Sandbox Code Playgroud)

那你应该没问题。

编辑:实际上它不是空值,而是导致异常的空 sourceType。

我使用反编译器进行了更深入的研究,看起来您得到的异常是因为 sourceType 为空。导致空引用异常的“IsValidValueForUpdate”函数仅在存在转换器时运行,这解释了为什么在删除转换器时没有得到它。代码在转换回来的过程中运行,这就解释了为什么它会以“OneWayToSource”作为绑定模式发生。无论如何,这可能只是框架中的一个小错误,因此在绑定之前设置 datacontext 以提供 sourceType 似乎是一个很好的解决方法。