WPF:从代码隐藏中取出命令处理程序时出现问题
我在 XAML 中定义了一些命令绑定:
<UserControl.CommandBindings>
<CommandBinding
Command="commands:Commands.GrantAccessCommand"
Executed="HelpExecuted" />
</UserControl.CommandBindings>
因此 GrantAccessCommand 位于一个名为 Commands 的单独类中,而 HelpExecuted 位于我的代码后面。效果很好。现在,当我将 HelpExecuted 也放入另一个类中时,我收到错误“...HelpExecuted”不是有效的事件处理程序方法名称。只有生成的或代码隐藏类上的实例方法才有效。”代码:
Executed="commands:Commands.HelpExecuted"
//I also tryed: Executed="x:Static commands:Commands.HelpExecuted"
我知道我可以使用 CommandBindings.Add(new CommandBinding(GrantAccessCommand, HelpExecuted)); 在代码后面执行此操作但我想使用 XAML 来做到这一点
有什么办法吗?
I have some command binding defined in my XAML:
<UserControl.CommandBindings>
<CommandBinding
Command="commands:Commands.GrantAccessCommand"
Executed="HelpExecuted" />
</UserControl.CommandBindings>
So GrantAccessCommand is located in a seperate class called Commands and HelpExecuted is in my code behind. It works fine. Now when I put HelpExecuted in the other class as well I get an error "...HelpExecuted' is not a valid event handler method name. Only instance methods on the generated or code-behind class are valid." The code:
Executed="commands:Commands.HelpExecuted"
//I also tryed: Executed="x:Static commands:Commands.HelpExecuted"
I know I can do this in code behind using CommandBindings.Add(new CommandBinding(GrantAccessCommand, HelpExecuted)); But I want to do this using XAML
Is there a way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的猜测是.Net 3.5。来自 http://www.codeproject.com/KB/WPF/CentralizingWPFCommands.aspx:当前WPF版本的XAML不允许我们以这种方式绑定事件处理程序。事件处理程序必须在 MainWindow 类内的代码隐藏文件中定义。我不知道这是一个错误,还是一个意外遗漏的功能,或者我们是否甚至不应该使用此功能,但这阻止我们定义一个集中位置来处理所有命令的 Executed 和 CanExecute 事件。
解决方法是在代码中定义绑定:
window.CommandBindings.Add(new CommandBinding(Help, HelpExecuted, HelpCanExecute));
My guess is .Net 3.5. From http://www.codeproject.com/KB/WPF/CentralizingWPFCommands.aspx: The current WPF version's XAML does not allow us to bind event handlers in this way. The event handlers must be defined in the code-behind file inside the MainWindow class. I don't know if this is a bug, an accidentally left out feature, or if we are not even supposed to use this functionality, but this stops us from defining a centralized location for handling all commands' Executed and CanExecute events.
The workaround is to define bindings in code:
window.CommandBindings.Add(new CommandBinding(Help, HelpExecuted, HelpCanExecute));
明白了:
定义你的命令:
在视图模型的构造函数中创建命令
在视图模型中公开命令:
在 XAMl 中绑定到它
Got it with this:
Define your command:
Create the command in the constructor of the view model
Expose command in your view model:
Bind to it in XAMl