user1151923
user1151923

Reputation: 1872

binding to the ToString() method in a DataTemplate

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>

Upvotes: 32

Views: 20014

Answers (5)

FelixFang
FelixFang

Reputation: 136

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();
    }
}

Upvotes: 7

Heysem Katibi
Heysem Katibi

Reputation: 1906

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.

Upvotes: 5

amnezjak
amnezjak

Reputation: 2031

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

Upvotes: 67

Geerten
Geerten

Reputation: 1057

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

Upvotes: 1

Jarek Kardas
Jarek Kardas

Reputation: 8455

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

Upvotes: 0

Related Questions