【发布时间】:2010-01-05 12:56:32
【问题描述】:
有什么办法可以让我在文本块上只显示绑定字符串的第一个字符..?
例如;如果我绑定“男性”,我的文本块应该只显示“M”.....
【问题讨论】:
标签: wpf binding textblock string-formatting
有什么办法可以让我在文本块上只显示绑定字符串的第一个字符..?
例如;如果我绑定“男性”,我的文本块应该只显示“M”.....
【问题讨论】:
标签: wpf binding textblock string-formatting
您可以使用值转换器返回字符串前缀:
class PrefixValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string s = value.ToString();
int prefixLength;
if (!int.TryParse(parameter.ToString(), out prefixLength) ||
s.Length <= prefixLength)
{
return s;
}
return s.Substring(0, prefixLength);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
在 XAML 中:
<Window.Resources>
...
<local:PrefixValueConverter x:Key="PrefixValueConverter"/>
</Window.Resources>
...
...{Binding Path=TheProperty, Converter={StaticResource PrefixValueConverter},
ConverterParameter=1}...
【讨论】:
NotImplementedException,而是抛出 NotSupportedException。 NIE 适用于尚未实现但即将实现的代码。这里:stackoverflow.com/questions/410719/…
s 比prefixLength 短,您将得到ArgumentOutOfRangeException。您的条件应该是:if (!int.TryParse(parameter.ToString(), out prefixLength) || s.Length <= prefixLength)