我正在创建一个 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/