binding to the ToString() method in a DataTemplate
Asked Answered
S

5

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>
Skid answered 29/11, 2012 at 15:23 Comment(0)
F
67

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

Failure answered 29/11, 2012 at 16:23 Comment(4)
This also works well when binding to an enum where you want to display the Enum.ToString().Lepido
how do you pass parmaeter to the ToString()method ? (for instance, for formatting a TimeSpan)Putdown
@Putdown Check the StringFormat parameterFailure
Also works with Text="{x:Bind}"Letterpress
P
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();
    }
}
Pak answered 29/11, 2012 at 15:27 Comment(1)
This worked for me. with a slight edit. return value != null ? value.ToString() : string.Empty;Davey
M
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.

Magnific answered 29/11, 2012 at 16:42 Comment(0)
L
1

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

Loom answered 29/11, 2012 at 16:12 Comment(0)
R
0

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

Rosenblast answered 29/11, 2012 at 15:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.