Doni Jose Mannanal
Doni Jose Mannanal

Reputation: 33

Silverlight : disable copy/paste/cut operations on textbox

I have requirement to disable copy/paste/cut operations on a textbox. For this purpose I inherited the Textbox and created MyTextbox and had the KeyDown event overriden with the following code

if (!(e.Key == Key.Back || e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Delete || e.Key == Key.Tab))
{
    if ((e.Key == Key.C || e.Key == Key.X || e.Key == Key.V) &&
                     (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
    {
        e.Handled = true;
    }
}

and then used this textbox. This textbox now prevents copy/paste/cut operations.

I am trying to acheive this same purpose using Behaviors.For this purpose I have created a behavior. The code is as under

public class MyTextboxBehavior : Behavior<TextBox>
{
        protected override void OnAttached()
        {
            base.OnAttached();

            this.AssociatedObject.KeyDown += new KeyEventHandler(AssociatedObject_KeyDown);
        }

        private void AssociatedObject_KeyDown(object sender, KeyEventArgs e)
        {
            if (!(e.Key == Key.Back || e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Delete || e.Key == Key.Tab))
            {
                if ((e.Key == Key.C || e.Key == Key.X || e.Key == Key.V) &&
                     (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
                {
                    e.Handled = true;
                }
            }
        }
}

and have added this behavior to Textbox as under

<TextBox>
     <Interactivity:Interaction.Behaviors>
          <CustomControl:MyTextboxBehavior></CustomControl:MyTextboxBehavior>
     </Interactivity:Interaction.Behaviors>
</TextBox>

Does anyone know why this is not working?

Upvotes: 3

Views: 1757

Answers (2)

Roberto
Roberto

Reputation: 1

        if (e.Key == Key.Ctrl)
            Clipboard.SetText(string.Empty);

Upvotes: 0

Anders Gustafsson
Anders Gustafsson

Reputation: 15981

UPDATED JUNE 24

In WPF, you would be able to capture the CTRL + X/C/V key presses at the PreviewKeyDown event, and then you would be able to suppress these functions in your text box.

In Silverlight Preview methods are not available, so here it is not an option. The TextBox control also has built-in handling of the clipboard actions copy and paste CTRL+C and CTRL+V (see Clipboard class remarks), so it is not straightforward to suppress these actions.

There is an attempt for an SL3 project here where the OnKeyDown and OnKeyUp event handlers are overridden in a class deriving from TextBox. The implementation calls the base methods which are obviously not accessible in the Behavior implementation, so a straightforward implementation of the copy and paste suppression in the TextBox via behaviors does not seem to be possible.

Upvotes: 2

Related Questions