Silverlight 4 TextBox中的字符外壳

时间:2010-11-04 14:23:59

标签: silverlight-4.0 textbox

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

还有其他方法可以达到这个目的吗?

3 个答案:

答案 0 :(得分: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;
    }
}

然后,在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>

其中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);

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

答案 1 :(得分:1)

试试这个:

private void txt2_KeyDown(object sender, KeyEventArgs e)
{
    e.Handled = MakeUpperCase((TextBox)sender, e);
}

bool MakeUpperCase(TextBox txt, KeyEventArgs e)
{
    if (Keyboard.Modifiers != ModifierKeys.None || (e.Key < Key.A) || (e.Key > Key.Z))  //do not handle ModifierKeys (work for shift key)
    {
        return false;
    }
    else
    {
        string n = new string(new char[] { (char)e.PlatformKeyCode });
        int nSelStart = txt.SelectionStart;

        txt.Text = txt.Text.Remove(nSelStart, txt.SelectionLength); //remove character from the start to end selection
        txt.Text = txt.Text.Insert(nSelStart, n); //insert value n
        txt.Select(nSelStart + 1, 0); //for cursortext

        return true; //stop to write in txt2
    }

}

答案 2 :(得分:0)

    private void txt2_KeyDown(object sender, KeyEventArgs e)
    {

        if (Keyboard.Modifiers != ModifierKeys.None) return; //do not handle ModifierKeys (work for shift key)

        string n = new string(new char[] { (char)e.PlatformKeyCode });
        int nSelStart = txt2.SelectionStart;

        txt2.Text = txt2.Text.Remove(nSelStart, txt2.SelectionLength); //remove character from the start to end selection
        txt2.Text = txt2.Text.Insert(nSelStart, n); //insert value n
        txt2.Select(nSelStart + 1, 0); //for cursortext

        e.Handled = true; //stop to write in txt2

    }