Silverlight 2.0 小技巧 (1) - 限制TextBox中輸入中文

有讀者來信問到Silverlight 2.0 中,能否TextBox無法輸入中文,
就目前的狀況看來,只能由KeyDown事件處理,如下所示:

 

 

有讀者來信問到Silverlight 2.0 中,能否TextBox無法輸入中文,

就目前的狀況看來,只能由KeyDown事件處理,如下所示:

 

1 <UserControl x:Class="SLGridDemo.DemoTextBox"
2     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
3     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
4     Width="400" Height="300">
5     <Canvas x:Name="LayoutRoot" Background="White">
6         <TextBox x:Name="txt1" Canvas.Top="50" Canvas.Left="50" Width="100" Text="" TextChanged="txt1_TextChanged" KeyDown="txt1_KeyDown"/>
7     </Canvas>
8 </UserControl>

.cs

 

01 using System;
02 using System.Collections.Generic;
03 using System.Linq;
04 using System.Net;
05 using System.Windows;
06 using System.Windows.Controls;
07 using System.Windows.Documents;
08 using System.Windows.Input;
09 using System.Windows.Media;
10 using System.Windows.Media.Animation;
11 using System.Windows.Shapes;

12
13 namespace SLGridDemo
14 {
15     public partial class DemoTextBox : UserControl
16     {
17         private string _baseText;
18         private int _selectStart;
19         private bool _deleteChanged = false;
20
21         public DemoTextBox()
22         {
23             InitializeComponent();
24         }

25
26         private void txt1_TextChanged(object sender, TextChangedEventArgs e)
27         {            
28             if (_deleteChanged)
29             {
30                 txt1.Text = _baseText;
31                 txt1.SelectionStart = _selectStart;
32                 _deleteChanged = false;
33             }

34         }

35
36         private void txt1_KeyDown(object sender, KeyEventArgs e)
37         {
38             _baseText = txt1.Text;
39             _selectStart = txt1.SelectionStart;
40             if (e.Key == Key.Unknown)
41                 _deleteChanged = true;
42         }

43     }

44 }

 

相反的,只能輸入中文的話,就得處理KeyDown事件及於TextChanged事件中偵測中文.