我如何使WPF文本框限制剪切、复制和粘贴操作?
我如何使WPF文本框限制剪切、复制和粘贴操作?
<TextBox CommandManager.PreviewExecuted="textBox_PreviewExecuted"
ContextMenu="{x:Null}" />
private void textBox_PreviewExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (e.Command == ApplicationCommands.Copy ||
e.Command == ApplicationCommands.Cut ||
e.Command == ApplicationCommands.Paste)
{
e.Handled = true;
}
}
e.Command == ApplicationCommands.Cut
,而不是进行类型转换,并依赖于可能由于本地化而更改的字符串。我向 Prashant 提交了编辑建议。 - VitalyB对于系统采用日语操作系统的情况,commandName方法将无法工作,因为commandName=="Paste"比较将失败。我尝试了下面的方法,并且它对我起作用。此外,我不需要手动禁用上下文菜单。
在XAML文件中:
<PasswordBox.CommandBindings>
<CommandBinding Command="ApplicationCommands.Paste"
CanExecute="CommandBinding_CanExecutePaste"></CommandBinding>
</PasswordBox.CommandBindings>
在代码后台:
private void CommandBinding_CanExecutePaste(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = false;
e.Handled = true;
}
Ctr+V
时它运行得很好。但是我注意到,当你右键单击密码框时,这个函数会被调用进入某种无限循环(如果你在这个函数中添加一个 msgbox,你就可以看到)。如何避免这种情况发生? - yem<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>
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)
{
}