So in my program I have an Entry
like so:
and this is bound to a property.
I ha
The answers here do answer the question you asked, which was "how do I convert the string that the user types to title case as they type," but I suspect the majority of use cases involve just setting the default for the field to be title case. I did not find the answer easily but have found this question repeatedly, so I hope this helps someone else.
See Customizing the Keyboard docs.
C#:
MyEntry.Keyboard = Keyboard.Create(KeyboardFlags.CapitalizeWord);
XAML:
<Entry Placeholder="Enter text here">
<Entry.Keyboard>
<Keyboard xmlns:FactoryMethod="Create">
<x:Arguments>
<KeyboardFlags>CapitalizeWord</KeyboardFlags>
</x:Arguments>
</Keyboard>
</Entry.Keyboard>
</Entry>
You can use Linq to split all the words and capitalize the first letter, something like this:
string input = "test of title case";
string output=String.Join(" ",input.Split(' ')
.ToList()
.Select(x => x = x.First().ToString().ToUpper() + x.Substring(1)));
In order for this to work, the separator of words must be a space always, it won't work with commas, periods etc...
I find a good solution on the following link:
https://www.codeproject.com/Tips/1004964/Title-Case-in-VB-net-or-Csharp
this solution take care about first-letter-capital and escape words such as the, a, in
public static class StringExtensions
{
public static string ToTitleCase(this string s)
{
var upperCase = s.ToUpper();
var words = upperCase.Split(' ');
var minorWords = new String[] {"ON", "IN", "AT", "OFF", "WITH", "TO", "AS", "BY",//prepositions
"THE", "A", "OTHER", "ANOTHER",//articles
"AND", "BUT", "ALSO", "ELSE", "FOR", "IF"};//conjunctions
var acronyms = new String[] {"UK", "USA", "US",//countries
"BBC",//TV stations
"TV"};//others
//The first word.
//The first letter of the first word is always capital.
if (acronyms.Contains(words[0]))
{
words[0] = words[0].ToUpper();
}
else
{
words[0] = words[0].ToPascalCase();
}
//The rest words.
for (int i = 0; i < words.Length; i++)
{
if (minorWords.Contains(words[i]))
{
words[i] = words[i].ToLower();
}
else if (acronyms.Contains(words[i]))
{
words[i] = words[i].ToUpper();
}
else
{
words[i] = words[i].ToPascalCase();
}
}
return string.Join(" ", words);
}
public static string ToPascalCase(this string s)
{
if (!string.IsNullOrEmpty(s))
{
return s.Substring(0, 1).ToUpper() + s.Substring(1).ToLower();
}
else
{
return String.Empty;
}
}
}
TextInfo textInfo = new CultureInfo("pt-BR", false).TextInfo;
entryName.Text = textInfo.ToTitleCase(entryName.Text);
You can use this
public static string ToTitle(this string data)
{
if (!string.IsNullOrEmpty(data))
{
TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;
return string.Format(textInfo.ToTitleCase(data.ToLower()));
}
return data;
}
Usage:
string test = "hello there";
test.ToTitle();