如何限制ValueConverter中的max char

时间:2016-07-21 03:04:42

标签: c# uwp

如何限制此TextBlock中的字符数?
例如:它最多只能显示5个字符。

<TextBlock >
    <Run Text="Tender Amount:"/>
    <Run Text="{Binding TenderAmount, 
                Converter={StaticResource StringFormatConverter}, 
                ConverterParameter='{}{0:C}'}" />
</TextBlock>

这是我的转换器中的代码

public sealed class StringFormatConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if (value == null)
            return null;

        if (parameter == null)
            return value;

        return string.Format((string)parameter, value);
    }

    public object ConvertBack(object value, Type targetType, object parameter,
        string language)
    {
        throw new NotImplementedException();
    }
}

1 个答案:

答案 0 :(得分:0)

使用此:

public sealed class StringFormatConverter : IValueConverter
{
    public int MaxLength { get; set; }

    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if (value == null)
            return null;

        if (parameter == null)
            return value;

        var result = string.Format((string)parameter, value);

        if (MaxLength > 0)
            result = result.Substring(0, MaxLength);

        return result;
    }

    public object ConvertBack(object value, Type targetType, object parameter,
        string language)
    {
        throw new NotImplementedException();
    }
}

在声明转换器资源的地方,请执行以下操作:

<stuff:StringFormatConverter x:Key="StringFormatConverter" MaxLength="5" />