有没有办法让我只能在文本块上显示一个Bound字符串的第一个字符..?
例如;如果我绑定'男',我的文本块只应显示'M'.....
答案 0 :(得分:13)
您可以使用值转换器返回字符串前缀:
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}...