Why won't WPF databindings show text when ToString() has a collaborating object?

Posted by Jay on Stack Overflow See other posts from Stack Overflow or by Jay
Published on 2010-05-26T19:22:54Z Indexed on 2010/05/27 1:21 UTC
Read the original article Hit count: 249

Filed under:
|
|
|
|

In a simple form, I bind to a number of different objects -- some go in listboxes; some in textblocks.

A couple of these objects have collaborating objects upon which the ToString() method calls when doing its work -- typically a formatter of some kind.

When I step through the code I see that when the databinding is being set up,

  1. ToString() is called
  2. the collaborating object is not null and returns the expected result
  3. when inspected in the debugger, the objects return the expected result from ToString()

BUT the text does not show up in the form.

The only common thread I see is that these use a collaborating object, whereas the other bindings that show up as expected simply work from properties and methods of the containing object.

If this is confusing, here is the gist in code:

public class ThisThingWorks
{
    private SomeObject some_object;

    public ThisThingWorks(SomeObject s) { some_object = s; }

    public override string ToString() { return some_object.name; }
}

public class ThisDoesntWork
{
    private Formatter formatter;
    private SomeObject some_object;

    public ThisDoesntWork(SomeObject o, Formatter f) 
    {
        formatter = f; 
        some_object = o;
    }

    public override string ToString()
    {
        return formatter.Format(some_object.name);
    }
}

Again, let me reiterate -- the ToString() method works in every other context -- but when I bind to the object in WPF and expect it to display the result of ToString(), I get nothing.

Update:

The issue seems to be what I see as a buggy behaviour in the TextBlock binding. If I bind the Text property to a property of the DataContext that is declared as an interface type, ToString() is never called. If I change the property declaration to an implementation of the interface, it works as expected. Other controls, like Label work fine when binding the Content property to a DataContext property declared as either the implementation or the interface.

Because this is so far removed from the title and content of this question, I've created a new question here: http://stackoverflow.com/questions/2917878/why-doesnt-textblock-databinding-call-tostring-on-a-property-whose-compile-tim

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET