wpf - 自动将文本框中的第一个字母大写

我正在创建一个 wpf 应用程序。我必须让所有文本框的首字母大写,如果用户输入的是小写的,那么在鼠标移出时应该将其格式化为大写。我需要最好的方法来做到这一点,请有人帮助我。

最佳答案

实现它的最佳方式在很大程度上取决于您如何使用您的应用程序,但@H.B. 的回答可能是可行的方式。
为了完整起见,另一种方法是使用这样的转换器:

<!-- 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}}" />

这假定您的窗口的数据上下文设置为一个类的实例,该类具有名为 SomeProperty 的字符串类型的读/写属性。 转换器本身是这样的:

// 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;
      }
    }
  }
}

您可以了解有关转换器的更多信息 here .

https://stackoverflow.com/questions/8026903/

相关文章:

c# - ASP.NET 中的虚拟路径

php - 如何使用某些 php 函数隐藏或编码 url?

haskell - 在 Haskell 中打印元组内的值

oracle - 检查临时表是否存在

networking - BGP 与 OSPF 和 IsIs

php - 使用 facebook sharer.php 与多个 url 变量共享一个 url

json - 将Json信息转换成F#列表

css - 如何并排显示两个高度为 100% 的 Div?

PHP PDO - 可以连接但查询不工作

php - 使用 PHP 检查字符串是否包含(CR、LF 或 CF 或 LF)或不包含