Silverlight 4 TextBox中的字符外壳

VRa*_*esh 2 textbox silverlight-4.0

我正在编写一个Silverlight 4业务应用程序,并遇到了一个问题.我需要TextBoxes中的文本输入强制为UpperCase.我从各种论坛了解的是Silverlight没有实现CharacterCasing和CSS样式.

有没有其他方法来实现这一目标?

Mur*_*ven 10

您可以通过创建行为来实现此目的,如下所示:

public class UpperCaseAction : TriggerAction<TextBox>
{

    protected override void Invoke(object parameter)
    {
        var selectionStart = AssociatedObject.SelectionStart;
        var selectionLenght = AssociatedObject.SelectionLength;
        AssociatedObject.Text = AssociatedObject.Text.ToUpper();
        AssociatedObject.SelectionStart = selectionStart;
        AssociatedObject.SelectionLength = selectionLenght;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,在TextBox中使用它,如下所示:

<Grid x:Name="LayoutRoot" Background="White">
    <TextBox TextWrapping="Wrap" VerticalAlignment="Top" Margin="10">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="TextChanged">
                <ASD_Answer009_Behaviors:UpperCaseAction/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </TextBox>
</Grid>
Run Code Online (Sandbox Code Playgroud)

i:名称空间在哪里

clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity

代码背后:

System.Windows.Interactivity.EventTrigger eventTrigger = new System.Windows.Interactivity.EventTrigger("TextChanged");
eventTrigger.Actions.Add(new UpperCaseAction());   
System.Windows.Interactivity.Interaction.GetTriggers(myTextBox).Add(eventTrigger);
Run Code Online (Sandbox Code Playgroud)

要创建和使用行为,您需要下载并安装适用于Silverlight 4Expression Blend SDK并添加对System.Windows.Interactivity.dll的引用.