2010-11-04 51 views
2

我正在編寫Silverlight 4業務應用程序並遇到問題。我需要將TextBoxes中的文本輸入強制爲UpperCase。我從各種論壇上了解到的是Silverlight沒有實現CharacterCasing和CSS樣式。Silverlight 4中的字符框文本框

是否有任何其他的方式來實現這一目標?

回答

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

然後,用它在你的文本框,就像這樣:

<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

+0

感謝。這很好用 – VRamesh 2010-11-05 01:46:50

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 

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

}