【发布时间】:2020-04-30 01:40:11
【问题描述】:
我正在学习 WPF。
在其中一个练习中,我有一个文本框和剪切和粘贴按钮。以下内容足以实现剪切和粘贴功能:
XAML:
<DockPanel>
<WrapPanel DockPanel.Dock="Top" Margin="3">
<Button Command="ApplicationCommands.Cut"
CommandTarget="{Binding ElementName=txtEditor}"
Width="60">
_Cut
</Button>
<Button Command="ApplicationCommands.Paste"
CommandTarget="{Binding ElementName=txtEditor}"
Width="60" Margin="3,0">
_Paste<
/Button>
</WrapPanel>
<TextBox AcceptsReturn="True" Name="txtEditor" />
</DockPanel>
按下按钮后,Cut 按钮会在名称为 txtEditor 的 TextBox 上执行 ApplicationCommands.Cut。需要时,该按钮会询问名为 textEditor 的 TextBox 是否可以执行剪切命令,按下时会命令 textEditor 执行剪切命令。
相当简单。它工作正常。
只是为了好玩,我想实现另一个按钮:清除。当按下它应该清除文本框。 Textbox 类有一个 Clear 方法。
<Button Command="ApplicationCommands.Clear"
CommandTarget="{Binding ElementName=txtEditor}"
Width="60">
Clear
</Button>
唉,这行不通。 ApplicationCommands 没有 Clear。我应该按照this example 中的建议实现自定义命令吗?
我尝试了以下方法:
我在我的窗口中实现了 CanExecute 和 Executed 方法:
public partial class CustomCommandSample : Window
{
public CustomCommandSample()
{
InitializeComponent();
}
private void ClearCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void ClearCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
txtEditor.Clear();
}
}
一个静态的 CustomCommands 类:
public static class CustomCommands
{
public static RoutedUICommand Clear => new RoutedUICommand (
"Clear",
"Clear",
typeof(CustomCommands));
}
最后是 XAML:
(注意:本项目中的类在命名空间 WpfCommandDemo 中,Xaml 将其称为Local)
<Window x:Class="WpfTutorialSamples.Commands.UsingCommandsSample"
xmlns="...
xmlns:local="clr-namespace:WpfCommandDemo"
Title="UsingCommandsSample" Height="100" Width="200">
<Window.CommandBindings>
<CommandBinding Command="CustomCommands.Clear"
CanExecute="ClearCommand_CanExecute"
Executed="ClearCommand_Executed" />
</Window.CommandBindings>
<DockPanel>
<WrapPanel DockPanel.Dock="Top" Margin="3">
<Button Command="CustomCommands.Clear"
CommandTarget="{Binding ElementName=txtEditor}"
Width="60">
Clear
</Button>
... (other buttons: cut / paste, as above
</WrapPanel>
<TextBox AcceptsReturn="True" Name="txtEditor" />
</DockPanel>
虽然可以编译,但 CustomCommandSample 的构造函数会抛出 XamlParseException:
Type reference cannot find type named
'{http://schemas.microsoft.com/winfx/2006/xaml/presentation}CustomCommands'.
我应该使用自定义命令解决问题吗?我应该改变什么?还是我完全错了,我应该以不同的方式解决这个问题
【问题讨论】:
-
你可以实现你自己的中继命令,看看这个thread