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>

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


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

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.

链接地址: http://www.djcxy.com/p/7762.html

上一篇: 当它是样式的一部分时如何绑定TextBlock Width

下一篇: 绑定到DataTemplate中的ToString()方法