【问题标题】:Wpf Binding Stringformat to show only first characterWpf Binding Stringformat 仅显示第一个字符
【发布时间】:2010-01-05 12:56:32
【问题描述】:

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

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

【问题讨论】:

    标签: wpf binding textblock string-formatting


    【解决方案1】:

    您可以使用值转换器返回字符串前缀:

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

    【讨论】:

    • 不要在 ConvertBack 中抛出 NotImplementedException,而是抛出 NotSupportedException。 NIE 适用于尚未实现但即将实现的代码。这里:stackoverflow.com/questions/410719/…
    • TBH,实际上还没有实现,听从你的建议,现在是:)
    • 是的..谢谢Aviad,实际上我希望避免使用转换器。但似乎没有办法...thx
    • 如果sprefixLength 短,您将得到ArgumentOutOfRangeException。您的条件应该是:if (!int.TryParse(parameter.ToString(), out prefixLength) || s.Length &lt;= prefixLength)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-28
    • 2012-08-17
    • 1970-01-01
    • 2021-09-11
    • 2019-06-10
    • 1970-01-01
    • 2014-10-21
    相关资源
    最近更新 更多