页面中TextBlock控件内容
<TextBlock x:Name="name" HorizontalAlignment="Left" Text="{Binding Name,Converter={StaticResource StringMaxLenConverter},ConverterParameter=13}" TextWrapping="NoWrap"/>
设置一个转换器,并且在页面中使用:
<convert:StringMaxLenConverter x:Key="StringMaxLenConverter" />
3、转换器类:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Data;
namespace Converters
{
public class StringMaxLenConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return string.Empty;
if (parameter == null)
return value;
int _MaxLength;
if (!int.TryParse(parameter.ToString(), out _MaxLength))
return value;
var _String = value.ToString();
if (_String.Length > _MaxLength)
_String = _String.Substring(0, _MaxLength);
return _String;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}