Reputation: 16923
How can I make a WPF textbox cut, copy and paste restricted?
Upvotes: 36
Views: 32815
Reputation: 135
<TextBox.CommandBindings>
<CommandBinding Command="ApplicationCommands.Cut"
PreviewExecuted="CommandBinding_PreviewExecutedCut"
Executed="CommandBinding_ExecutedCut"/>
<CommandBinding Command="ApplicationCommands.Copy"
PreviewExecuted="CommandBinding_PreviewExecutedCopy"
Executed="CommandBinding_ExecutedCopy"/>
<CommandBinding Command="ApplicationCommands.Paste"
PreviewExecuted="CommandBinding_PreviewExecutedPaste"
Executed="CommandBinding_ExecutedPaste"/>
</TextBox.CommandBindings>
In the code behind:
private void CommandBinding_PreviewExecutedCut(object sender, ExecuteRoutedEventArgs e)
{
e.Handled = true;
}
private void CommandBinding_ExecutedCut(object sender, ExecuteRoutedEventArgs e)
{
}
private void CommandBinding_PreviewExecutedCopy(object sender, ExecuteRoutedEventArgs e)
{
e.Handled = true;
}
private void CommandBinding_ExecutedCopy(object sender, ExecuteRoutedEventArgs e)
{
}
private void CommandBinding_PreviewExecutedPaste(object sender, ExecuteRoutedEventArgs e)
{
e.Handled = true;
}
private void CommandBinding_ExecutedPaste(object sender, ExecuteRoutedEventArgs e)
{
}
Panda gave me a good idea. The funny thing is the PreviewExecuted did not fire for me unless I also subscribed to Executed. I like it better than Panda because there is no excessive looping. I like it better then Cholachagudda because his approach hid my cursor sometimes.
Upvotes: 1
Reputation: 13090
Cut, Copy, and Paste are the common commands used any application.
<TextBox CommandManager.PreviewExecuted="textBox_PreviewExecuted"
ContextMenu="{x:Null}" />
In the above textbox code we can restrict these commands in PreviewExecuted event of CommandManager Class.
In the code behind add the code below and your job is done.
private void textBox_PreviewExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (e.Command == ApplicationCommands.Copy ||
e.Command == ApplicationCommands.Cut ||
e.Command == ApplicationCommands.Paste)
{
e.Handled = true;
}
}
Upvotes: 54
Reputation: 332
The commandName method will not work on a System with Japanese OS as the commandName=="Paste" comparision will fail. I tried the following approach and it worked for me. Also I do not need to disable the context menu manually.
In the XaML file:
<PasswordBox.CommandBindings>
<CommandBinding Command="ApplicationCommands.Paste"
CanExecute="CommandBinding_CanExecutePaste"></CommandBinding>
</PasswordBox.CommandBindings>
In the code behind:
private void CommandBinding_CanExecutePaste(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = false;
e.Handled = true;
}
Upvotes: 19