Initialize the first letter in TextBox

advertisements

I am creating a wpf application. I have to make all textbox first letter to capital, if a user entered in small then it should be formatted in capital on mouse out.I need the best way to do it, please someone help me.


The best way of doing it greatly depends on how you are doing your app, but @H.B.'s answer is probably the way to go.
For the sake of completeness, another way if doing it would be to use a converter like so:

<!-- Your_Window.xaml -->
<Window x:Class="..."
        ...
        xmlns:cnv="clr-namespace:YourApp.Converters">
  <Window.Resources>
    <cnv.CapitalizeFirstLetterConverter x:Key="capFirst" />
  </Window.Resources>
  ...
  <TextBox Text="{Binding Path=SomeProperty, Converter={StaticResource capFirst}}" />

This assumes that your window's data context is set to an instance of a class that has a read/write property named SomeProperty of type string. The converter itself would be something like this:

// CapitalizeFirstLetterConverter.cs
using System;
using System.Data;
using System.Globalization;
namespace YourApp.Converters {
  [ValueConversion(typeof(string), typeof(string))]
  public class CapitalizeFirstLetterConverter : IValueConverter {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
      // this will be called after getting the value from your backing property
      // and before displaying it in the textbox, so we just pass it as-is
      return value;
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
      // this will be called after the textbox loses focus (in this case) and
      // before its value is passed to the property setter, so we make our
      // change here
      if (value is string) {
        var castValue = (string)value;
        return char.ToUpper(castValue[0]) + castValue.Substring(1);
      }
      else {
        return value;
      }
    }
  }
}

You can learn more about converters here.