I have a name such as Jonny Bravo, and I would like my label to reflect the initials of that name (JB) through Binding. How can I?
I need a code entirely through XAML/Binding and possible ValueConverter if needed. Any suggestions?
I have a name such as Jonny Bravo, and I would like my label to reflect the initials of that name (JB) through Binding. How can I?
I need a code entirely through XAML/Binding and possible ValueConverter if needed. Any suggestions?
Use a ValueConverter.
Converter:
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 use:
<TextBox Text="{Binding Name, Converter={StaticResource InitialsConverter}}" />
Fill the Initials Property inside the Setter of the FullName Property at your viewModel
Public string FullName{
...
Set{
this.fullName = value;
this.Initials = GenerateInitialsFromFullName();
}
Or create an ValueConverter as already suggested.
Using a value converter would be the way to go because it's reusable in other places in your code if needed.
Here's a quick one I threw together using Regex to find the first letters (note that splitting the string would offer better performance).
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();
}
}
Usage:
<!--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}}"/>
No converter:
Using converter:
InitialsConverter.Convert
method and step through -- you may be able to work out what's wrong this way.
Mar 3, 2015 at 21:20