2

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'.....

biju
  • 17,554
  • 10
  • 59
  • 95

1 Answers1

15

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}...
Aviad P.
  • 32,036
  • 14
  • 103
  • 124
  • 1
    Instead of throwing `NotImplementedException` in ConvertBack, throw `NotSupportedException`. NIE is for code that is not yet implemented but will be soon. Here: http://stackoverflow.com/questions/410719/notimplementedexception-are-they-kidding-me – R. Martinho Fernandes Jan 05 '10 at 13:15
  • TBH, It was actually not implemented yet, taking your advice, it now is :) – Aviad P. Jan 05 '10 at 13:43
  • Yes..thanks Aviad,Actually i was looking to avoid using a converter.But seems like there is no way around...thx – biju Jan 07 '10 at 18:25
  • You will get ArgumentOutOfRangeException in case `s` is shorter than `prefixLength`. Your condition should be: `if (!int.TryParse(parameter.ToString(), out prefixLength) || s.Length <= prefixLength)` – tom.maruska Jun 02 '15 at 14:35