32

Is there any easy way to bind to the ToString() method in a DataTemplate? I would expect the Text property of a TextBlock to use ToString() by default for its Text property, but that does not happen. So any easy way to do this:

<DataTemplate x:Key="myTemplate">
    <TextBlock Text="{Binding ToString()}"/>
<DataTemplate>
Askolein
  • 3,250
  • 3
  • 28
  • 40
user1151923
  • 1,853
  • 6
  • 28
  • 44

5 Answers5

67

You can use Text="{Binding}". The ToString() method is invoked implicitly.

amnezjak
  • 2,011
  • 1
  • 14
  • 18
7

you can use a Converter. like this:

public class PropertyValueStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value.ToString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
Maljam
  • 6,244
  • 3
  • 17
  • 30
FelixFang
  • 136
  • 3
  • This worked for me. with a slight edit. return value != null ? value.ToString() : string.Empty; – Jgraham Jun 13 '13 at 14:38
5

Unfortunately, you cant bind control to method but you can circumvent to do that look:

public string GetText()
{
    return "I am happy";
}

public string MyText
{
    get { return GetText(); }
}

Now in XAML:

<DataTemplate x:Key="myTemplate">
    <TextBlock Text="{Binding MyText}"/>
<DataTemplate>

be careful MyText property must be in the context of the window.

Heysem Katibi
  • 1,808
  • 2
  • 14
  • 29
1

It would make more sense to add a string property, for that specific ToString() method, to the object you are binding to.

Geerten
  • 1,027
  • 1
  • 9
  • 22
0

WPF does not support binding to methods directly, but you could use custom IValueConverter, ObjectDataProvider or any other approach as described here.

Community
  • 1
  • 1
Jarek Kardas
  • 8,445
  • 1
  • 31
  • 32