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?
UPDATED JUNE 24
In WPF, you would be able to capture the CTRL + X/C/V key presses at the
PreviewKeyDownevent, 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
TextBoxcontrol also has built-in handling of the clipboard actions copy and pasteCTRL+CandCTRL+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
OnKeyDownandOnKeyUpevent handlers are overridden in a class deriving fromTextBox. The implementation calls thebasemethods which are obviously not accessible in theBehaviorimplementation, so a straightforward implementation of the copy and paste suppression in theTextBoxvia behaviors does not seem to be possible.