这里以TEXTBOX控件为例子
1.先在界面编辑建立两个textbox控件,包含属性中比较重要的是禁用输入法和输入数据的预处理函数的设定,预输入处理函数将使得TEXTBOX只能输入数字相关的符号
<TextBox x:Name="tbX" HorizontalAlignment="Left" Height="23" Margin="84,495,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="70" MouseWheel="numberWheelchange" PreviewTextInput="tb_PreviewTextInput" InputMethod.IsInputMethodEnabled="False"/>
<TextBox x:Name="tbY" HorizontalAlignment="Left" Height="23" Margin="206,495,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="70" MouseWheel="numberWheelchange" PreviewTextInput="tb_PreviewTextInput" InputMethod.IsInputMethodEnabled="False"/>
设置输入法禁用:InputMethod.IsInputMethodEnabled="False"
设置输入数据的预先处理函数:PreviewTextInput="tb_PreviewTextInput"
设置滚轮动作执行函数:MouseWheel="numberWheelchange"
2.预处理函数只允许输入负号和数字和小数点,这里是通过正则表达式来实现的
private void tb_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
Regex re = new Regex("[^0-9.-]+");
e.Handled = re.IsMatch(e.Text);
}
3.滚轮动作的代码执行部分,先判别当前激活的控件,是否有数值,随后是对数值的变更
private void numberWheelchange(object sender, MouseWheelEventArgs e)
{
if(tbX.IsSelectionActive)
{
if(tbX.Text != null)
{
tbX.Text = (Convert.ToInt16(tbX.Text) + e.Delta/120).ToString();
}
}
if(tbY.IsSelectionActive)
{
if (tbY.Text != null)
{
tbY.Text = (Convert.ToInt16(tbY.Text) + e.Delta / 120).ToString();
}
}
}