在WPF资源文件中的按钮中绑定命令可以通过以下步骤实现:
在资源文件中定义命令对象,例如:
<Window.Resources>
<RoutedUICommand x:Key="MyCommand"/>
</Window.Resources>
接着在按钮中使用Command属性绑定命令对象,例如:
<Button Content="Click Me" Command="{StaticResource MyCommand}" />
在绑定的命令对象中定义命令处理程序,例如:
public partial class MainWindow : Window
{
public static RoutedCommand MyCommand = new RoutedCommand();
public MainWindow()
{
InitializeComponent();
CommandBinding binding = new CommandBinding(MyCommand, MyCommand_Executed, MyCommand_CanExecute);
this.CommandBindings.Add(binding);
}
private void MyCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void MyCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("My command executed!");//这里写你想执行的命令语句
}
}
在上面的例子中,我定义了一个静态的RoutedCommand对象MyCommand,并在MainWindow的构造函数中为它添加了一个CommandBinding,指定了它的CanExecute和Executed事件的处理程序。在MyCommand_CanExecute方法中,设置了命令可以执行的条件为true,在MyCommand_Executed方法中,展示了一个简单的消息框。这样,当我们在WPF资源文件中定义的按钮被点击时,就会触发MyCommand_Executed方法,展示出消息框。