我有一个名字,如Jonny Bravo,我希望我的标签通过Binding来反映该名称(JB)的首字母。我怎么能?
我需要一个代码完全通过XAML / Binding和可能的ValueConverter(如果需要)。有什么建议吗?
答案 0 :(得分:1)
使用ValueConverter。
转换器:
public class InitialsConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string s = value as string;
string i = string.Empty;
if (s != null)
{
string[] split = s.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach (string piece in split)
{
i += piece[0];
}
}
return i;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Xaml使用:
<TextBox Text="{Binding Name, Converter={StaticResource InitialsConverter}}" />
答案 1 :(得分:0)
在viewModel
的FullName属性的Setter中填充Initials属性Public string FullName{
...
Set{
this.fullName = value;
this.Initials = GenerateInitialsFromFullName();
}
或者按照建议创建一个ValueConverter。
答案 2 :(得分:0)
使用值转换器是可行的方法,因为如果需要,它可以在代码中的其他位置重复使用。
这是一个快速的,我使用正则表达式找到第一个字母(请注意,分割字符串将提供更好的性能)。
public class InitialsConverter : IValueConverter
{
public virtual object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string str = value as string;
if (str != null)
{
string s = "";
MatchCollection matches = Regex.Matches(str, @"(\b\w)");
foreach (Match m in matches)
s += m.Value;
return s;
}
else
{
return null;
}
}
public virtual object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
用法:
<!--Declare in your scope's resources-->
<Window.Resources>
<r:InitialsConverter x:Key="initials"/>
</Window.Resources>
<!--Bind to a string using the converter-->
<TextBlock Text="{Binding MyName, Converter={StaticResource initials}}"/>
没有转换器:
使用转换器: