2011-11-06 68 views
1

我正在创建一个wpf应用程序。我必须把所有的文本框首字母大写,如果用户输入小,那么它应该用鼠标大写格式化。我需要最好的方式来做到这一点,请别人帮助我。自动大写文本框中的第一个字母

回答

3

极大地做它的最佳方法取决于你如何做你的应用程序,但@ 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

+0

谢谢老兄,我一直在寻找somethink这样............ – Anu

+2

此外,在文本绑定,如果你把'UpdateSourceTrigger = PropertyChanged',该转换器将运行而不是当TextBox失去焦点时。 –

1

您可以将样式放入Application.Resources以处理所有TextBoxes上的LostFocus,那么您只需相应地更改Text属性。

<!-- App.xaml - Application.Resources --> 
<Style TargetType="{x:Type TextBox}"> 
    <EventSetter Event="LostFocus" Handler="TextBox_LostFocus" /> 
</Style> 
// App.xaml.cs - App 
private void TextBox_LostFocus(object sender, RoutedEventArgs e) 
{ 
    var tb = (TextBox)sender; 
    if (tb.Text.Length > 0) 
    { 
     tb.Text = Char.ToUpper(tb.Text[0]) + tb.Text.Substring(1); 
    } 
} 
相关问题