1

你能帮我解决我的问题吗?我想阻止我的文本框的粘贴并控制所有字符都是数字(WinRT)。

4

4 回答 4

2

从 Windows 8.1 开始,您将获得一个可以订阅的“粘贴”事件。只需订阅它并将事件的Handled属性设置为true以阻止它到达 TextBox。

于 2013-10-22T07:48:21.423 回答
1

UPDATE 1

If you want to prevent ctrl + c & ctrl + v combination, then you have to check that combination in KeyDown event. If you get that combination you can clear the clipboard with static method Windows.ApplicationModel.DataTransfer.Clipboard.Clear();

If you don't watch for combination of keys rather then just ctrl, then also you can prevent the copy pasting via keyboards.

private void TextBox_KeyDown_1(object sender, KeyRoutedEventArgs e)
{
    if (e.Key == Windows.System.VirtualKey.Control)
        Windows.ApplicationModel.DataTransfer.Clipboard.Clear();
}

To allow user to enter only numeric data you can use TextBox's TextChanged event. Use numeric only regular expression to filter out the characters. Moreover to disable context menu of TextBox, ContextMenuOpening event will help you. Below is the whole code.

XAML

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
    <TextBox Height="50" Width="300" TextChanged="TextBox_TextChanged_1" ContextMenuOpening="TextBox_ContextMenuOpening_1" />
</Grid>

C#

private void TextBox_TextChanged_1(object sender, TextChangedEventArgs e)
{
    var tb = (TextBox)sender;
    var IsNumeric = new System.Text.RegularExpressions.Regex("^[0-9]*$");
    var text = tb.Text;
    if (!IsNumeric.IsMatch(text))
    {
        int CursorIndex = tb.SelectionStart - 1;
        tb.Text = tb.Text.Remove(CursorIndex, 1);
        tb.SelectionStart = CursorIndex;
        tb.SelectionLength = 0;
    }
}

private void TextBox_ContextMenuOpening_1(object sender, ContextMenuEventArgs e)
{
    e.Handled = true;
}
于 2013-06-11T07:08:44.627 回答
1

阻止粘贴: 1. 阻止粘贴事件

    txtBox1.Paste += ADDTextBox_Paste;

    void ADDTextBox_Paste(object sender, TextControlPasteEventArgs e) 
    {e.Handled = true;return; }
  1. 阻止 shift + insert 和 Ctrl + V 的 Keydown 事件。

    void txtBox1_KeyDown(object sender, KeyRoutedEventArgs e)
        {            
            var shiftState = CoreWindow.GetForCurrentThread().GetKeyState(VirtualKey.Shift);
            var ctrlState = CoreWindow.GetForCurrentThread().GetKeyState(VirtualKey.Control);
    
            if (((shiftState & CoreVirtualKeyStates.Down) == CoreVirtualKeyStates.Down && e.Key == VirtualKey.Insert)
                ||((ctrlState & CoreVirtualKeyStates.Down) == CoreVirtualKeyStates.Down && e.Key == VirtualKey.V))
            {
                e.Handled = true; 
                return; 
            }                       
        }
    

要仅允许数字字符,您必须在 Keydown 事件中添加此代码:

if ((e.Key < VirtualKey.Number0 || e.Key > VirtualKey.Number9) &&
(e.Key < VirtualKey.NumberPad0 || e.Key > VirtualKey.NumberPad9))
{ e.handled = true; return; }
于 2015-06-23T13:06:42.990 回答
-1

使用 Shift A 阻止整个通道。向上或向下移动箭头以阻止小零件。右键单击阻塞的通道以“复制”并粘贴。

于 2013-07-12T05:04:21.547 回答