Wpf Binding Stringformat to show only first character

前端 未结 1 1021
耶瑟儿~
耶瑟儿~ 2020-12-20 03:46

Is there any way so that i can show only first character of a Bound string on a textblock..?

For eg;If i Bind \'Male\', my textblock should only show \'M\'.....

相关标签:
1条回答
  • 2020-12-20 04:14

    You might use a value converter to return a string prefix:

    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();
        }
    }
    

    And in XAML:

    <Window.Resources>
        ...
        <local:PrefixValueConverter x:Key="PrefixValueConverter"/>
    </Window.Resources>
    ...
    ...{Binding Path=TheProperty, Converter={StaticResource PrefixValueConverter},
                                  ConverterParameter=1}...
    
    0 讨论(0)
提交回复
热议问题