Reputation: 39095
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.
Upvotes: 1
Views: 2212
Reputation: 3512
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.
Upvotes: 2