Click here to Skip to main content
16,015,623 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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();
        }


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

Can anybody help me regarding this?

Thanks in Advance.
Posted
Updated 16-Jun-10 4:27am
v2

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

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


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);
 
Share this answer
 
v2
For an alternate approach to what you are trying above, see here.
 
Share this answer
 
Hai.... thanks that alternative i know, but here the textbox is creating dynamically in wpf form so i cant write the xaml code there.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900