禁止在WPF文本框中粘贴(Ctrl + V). [英] Disallowing paste (Ctrl+V) in a WPF TextBox.

查看:505
本文介绍了禁止在WPF文本框中粘贴(Ctrl + V).的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从UserControl(这是一个TextBox UserControl)动态地绑定WPF窗口中的TextBox,并且它不应允许用户将(Ctrl + V)文本粘贴到textBox中.因此,我已在后面的代码中编写了此代码,并对这种方法感到震惊.

I am binding a TextBox in a WPF window dynamically from a UserControl(which is a TextBox UserControl) and it should not allow the user to Paste(Ctrl+V) text into the textBox. So I have written this code in code behind and got struck up at this method.

private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            UserControl1 ntb = new UserControl1();
            ntb.Margin = new Thickness(5, 2, 10, 2);

            //KeyBinding kb = new KeyBinding(ApplicationCommands.NotACommand, Key.V, ModifierKeys(Key.Left));
            KeyBinding kb = new KeyBinding();
            kb.Command = ApplicationCommands.NotACommand;
            kb.Key = Key.V;
            kb.Modifiers = ModifierKeys(Key.LeftCtrl);
            
           
            ntb.textBox1.InputBindings.Add(kb);
        }

        private ModifierKeys ModifierKeys(Key key)
        {
            throw new NotImplementedException();
        }



*****所以我应该在方法ModifierKeys(Key key)中写什么才能返回.

有人可以帮我吗?

在此先感谢.



***** So what shouldIi write in the method ModifierKeys(Key key) to return.

Can anybody help me regarding this?

Thanks in Advance.

推荐答案


我认为Abhinav的解决方案很好.其中说明了如何使用xaml和动态代码禁用粘贴命令.

Hi,
I think Abhinav''s solution is good.There explains how to disable the paste command using xaml and by code dynamically.

DataObject.AddPastingHandler(ntb.textBox1, new DataObjectPastingEventHandler(OnPasteCommand));



将事件处理程序用作



use the event handler as

void  OnPasteCommand(object sender, DataObjectPastingEventArgs e)
   {
     e.CancelCommand();
   }



如果您想使用自己的方法,这里的问题是Paste命令没有在Ctrl + v上执行,但是仍然可以通过文本框的上下文菜单进行粘贴.仍然要选择自己的方法,您可以使用像
这样的代码



If you would like to use your approch,the problem here is the Paste command doesn''t execute on Ctrl+v but it still possible to paste through the context menu of textbox.Still you would like to choose your approch you can use the code like

KeyBinding vBinding = new KeyBinding(ApplicationCommands.NotACommand,new KeyGesture(Key.V, ModifierKeys.Control));
      ntb.textBox1.InputBindings.Add(vBinding);


有关上述内容的替代方法,请参见
For an alternate approach to what you are trying above, see here.


Hai ....谢谢我知道可以替代,但是这里的文本框是以wpf形式动态创建的,因此我无法在其中编写xaml代码.
Hai.... thanks that alternative i know, but here the textbox is creating dynamically in wpf form so i cant write the xaml code there.


这篇关于禁止在WPF文本框中粘贴(Ctrl + V).的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆