1

Say I have a class like this:

public class MyClass
{
    public string Name;
    public int Id;

    public override string ToString()
    {
        return this.Id.ToString() + " - " + this.Name;
    }
}

If I bind a datagrid text column to an object instance of this class (without using a converter), the overridden ToString is called and displays the Id - Name successfuly. However, when I bind the same object to a TextBlock's Text property, the ToString is never called and Text is empty. I know I could use a converter, but I'm trying to understand why the binding doesn't call the ToString like it does when I bind to the datagrid column.

Datagrid column binding (datagrid's item source is a collection of MyClass objects):

<DataGridTextColumn Binding="{Binding .}" Header="Id - Name"/>

TextBlock binding:

<TextBlock><Run Text="{Binding myClass, ElementName=UserControl}"/></TextBlock>

Note: if I change myClass to myClass.Name, then it successfully displays the Name property.

H.B.
  • 166,899
  • 29
  • 327
  • 400
Eren Ersönmez
  • 38,383
  • 7
  • 71
  • 92
  • I just tried adding Mode=OneWay to the TextBlock's binding expression ({Binding myClass, ElementName=UserControl, Mode=OneWay}) and it worked! Now I'm even more curious to know what's going on behind the scenes. – Eren Ersönmez Dec 28 '11 at 09:05
  • 2
    Did you look on VS `output` to see what failed binding, in case of `TextBox`, reports? – Tigran Dec 28 '11 at 09:08
  • Thanks. Didn't realize VS outputs errors for binding failures, thinking they were silent errors under the hood. When I look at the output I do see: "System.Windows.Data Error: 1 : Cannot create default converter to perform 'two-way' conversions between types 'Example.MyClass' and 'System.String'. Consider using Converter property of Binding ..." – Eren Ersönmez Dec 28 '11 at 14:16
  • Deducting from this, just guess, that `TextBox` like a *default* binding has 2 way. To prove this, you can try to specify one way binding for `TextBox` (only read) and see if it works. If yes, that is actual explanation:) – Tigran Dec 28 '11 at 16:45
  • @Tigran: One of you people should post an answer (so it can be accepted)... – H.B. Jan 13 '12 at 18:00

1 Answers1

2

There are certain conversions for which WPF will apply an implicit converter on a binding if the bound types don't match. Converting to a string can be done by calling ToString() the same way it's implicitly called in other areas of the .Net framework.

The Text binding of the TextBox is two-way by default and therefore can't use an implicit converter as a string can't be converted back to your MyClass type. The binding for the display template in the grid column is one way and can therefore use an implicit converter. I would imagine that you would get a binding error if you put the grid column into edit mode by clicking on it.

Kai G
  • 3,371
  • 3
  • 26
  • 30