绑定到DataTemplate中的ToString()方法

use*_*923 26 c# wpf xaml datatemplate

有没有简单的方法绑定到DataTemplate中的ToString()方法?我希望TextBlock的Text属性默认使用ToString()作为Text属性,但这不会发生.所以任何简单的方法:

<DataTemplate x:Key="myTemplate">
    <TextBlock Text="{Binding ToString()}"/>
<DataTemplate>
Run Code Online (Sandbox Code Playgroud)

amn*_*jak 50

你可以用Text="{Binding}".ToString()隐式调用该方法.


小智 6

你可以使用转换器.像这样:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)


Hey*_*ibi 5

不幸的是,您无法将控件绑定到方法,但您可以规避这样做:

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

public string MyText
{
    get { return GetText(); }
}
Run Code Online (Sandbox Code Playgroud)

现在在 XAML 中:

<DataTemplate x:Key="myTemplate">
    <TextBlock Text="{Binding MyText}"/>
<DataTemplate>
Run Code Online (Sandbox Code Playgroud)

请注意,MyText 属性必须位于窗口的上下文中。