Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(WPF) Binding OneWayToSource with a converter results in immediate exception

I've a TextBox in a window which I'm binding to a value with the following trivial converter:

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";
    }
}

The binding itself is manifesting like so:

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

If I remove either the converter or set the mode to TwoWay no exception is raised. Why is an exception being raised otherwise, and how can I resolve or at least work around the issue?

Edit: It seems one has to provide a data context in this scenario before binding for there to be no exception raised. Why is it so?

like image 930
Kaganar Avatar asked Apr 18 '13 21:04

Kaganar


1 Answers

I believe you are getting that error because you are binding the TextBox.TextProperty to nm, but the TextBox.TextProperty is null. With a two way binding it must send the value from nm to the TextBox.TextProperty first, setting it to "x", so that its not null anymore when it tries to bind back the other way. Removing the converter probably also removes the check that discovers that the TextBox.TextProperty is null and produces the exception.

So, if you were to add the line:

oj.Fe.Text = "something";

Or possibly even:

oj.Fe.Text = string.Empty;

before

oj.Fe.SetBinding(TextBox.TextProperty, bnd);

then you should be ok.

EDIT: Actually it wasn't a null value but a null sourceType that caused the exception.

I looked in deeper with a decompiler and it looks like the exception you get is because the sourceType is null. The "IsValidValueForUpdate" function which causes the null reference exception only runs when there is a converter, which explains why you dont get it when you remove the converter. The code was run in the process of converting back, which explains why it happens with "OneWayToSource" as the binding mode. Regardless, it may just be a minor bug in the framework, so setting the datacontext before binding to provide the sourceType seems to be a good workaround.

like image 104
Ben Wilde Avatar answered Sep 25 '22 23:09

Ben Wilde