wpf 绑定到 DataTemplate 中的 ToString() 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13628994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
binding to the ToString() method in a DataTemplate
提问by user1151923
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 中的 ToString() 方法?我希望 TextBlock 的 Text 属性默认使用 ToString() 作为其 Text 属性,但这不会发生。所以任何简单的方法来做到这一点:
<DataTemplate x:Key="myTemplate">
<TextBlock Text="{Binding ToString()}"/>
<DataTemplate>
回答by amnezjak
You can use Text="{Binding}". The ToString()method is invoked implicitly.
您可以使用Text="{Binding}". 该ToString()方法是隐式调用的。
回答by FelixFang
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();
}
}
回答by Heysem Katibi
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:
现在在 XAML 中:
<DataTemplate x:Key="myTemplate">
<TextBlock Text="{Binding MyText}"/>
<DataTemplate>
be careful MyText property must be in the context of the window.
小心 MyText 属性必须在窗口的上下文中。
回答by Geerten
It would make more sense to add a string property, for that specific ToString() method, to the object you are binding to.
为特定的 ToString() 方法向要绑定的对象添加字符串属性会更有意义。

