Wpf Binding Stringformat仅显示第一个字符

bij*_*iju 2 wpf binding textblock string-formatting

有什么方法可以让我只能在文本块上显示一个Bound字符串的第一个字符..?

例如;如果我绑定'男',我的文本块应该只显示'M'.....

Avi*_* P. 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

在XAML中:

<Window.Resources>
    ...
    <local:PrefixValueConverter x:Key="PrefixValueConverter"/>
</Window.Resources>
...
...{Binding Path=TheProperty, Converter={StaticResource PrefixValueConverter},
                              ConverterParameter=1}...
Run Code Online (Sandbox Code Playgroud)