You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF自定义RoutedCommand报错:无法找到目标类型的成员

问题原因与修正方案

你的错误出在CommandBinding的Command绑定路径上:{x:Static local:TestCommands}只引用了静态类本身,而没有指向类中定义的MyCommand静态属性,XAML无法识别要绑定的具体命令成员,因此报错。

修正步骤:

  1. 修改XAML中的CommandBinding,明确指定静态属性MyCommand:
<Window.CommandBindings>
    <CommandBinding Command="{x:Static local:TestCommands.MyCommand}" 
                    Executed="MyCommand_Executed"
                    CanExecute="MyCommand_CanExecute"/>
</Window.CommandBindings>
  1. 在后台代码中添加命令的执行与可用性判断方法(必须实现,否则命令无法触发):
private void MyCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
    // 这里写命令触发后的逻辑,比如弹窗、业务操作等
    MessageBox.Show("自定义命令执行成功!");
}

private void MyCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    // 设置命令是否可用,这里直接设为true,也可以根据业务逻辑动态判断
    e.CanExecute = true;
}

额外优化建议(非强制):

你的C#代码中,静态字段命名不符合C#规范,建议调整为私有下划线开头的字段,保持代码风格一致:

public static class TestCommands
{
    private static readonly RoutedCommand _myCommand = new RoutedCommand("MyCommand", typeof(TestCommands));
    public static RoutedCommand MyCommand => _myCommand;
}

内容的提问来源于stack exchange,提问作者ErraticFox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 02:57:04