Wpf Binding Stringformat to show only first character

纵然是瞬间 提交于 2019-12-18 07:06: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:


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


来源:https://stackoverflow.com/questions/2006111/wpf-binding-stringformat-to-show-only-first-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!