wpf eventsetter处理程序绑定样式
我有一个样式,我想将命令绑定到EventSetter
的Handler
with RelativeSource
。 该命令位于viewModel中。
问题是我得到一个错误,因为这有什么问题(也许不可能以这么简单的方式做到这一点)
我之前用Google搜索了很多东西,然后我找到了AttachedCommandBehaviour
,但我认为它不适用于样式。
你能给出一些如何解决这个问题的提示吗?
更新13/10/2011
我在MVVM Light Toolkit EventToCommand
示例程序中找到了这个:
但在这里,绑定不是风格。 如何将此EventToCommand
置于按钮样式?
现在,您将MouseLeftButtonDown
事件绑定到TextBlock.TextBlockMouseLeftButtonDownCommand
。 TextBlockMouseLeftButtonDownCommand
不是TextBlockMouseLeftButtonDownCommand
的有效属性,也不是它的事件处理程序。
我一直在样式中使用AttachedCommandBehavior将命令连接到事件。 语法通常如下所示(注意命令绑定中的DataContext
):
另一种方法是将EventSetter挂钩到代码隐藏中的事件,并从那里处理命令:
代码中的事件处理程序…
void TextBlockMouseLeftButtonDown(object sender, MouseEventArgs e) { var tb = sender as TextBlock; if (tb != null) { MyViewModel vm = tb.DataContext as MyViewModel; if (vm != null && TextBlockMouseLeftButtonDownCommand != null && TextBlockMouseLeftButtonDownCommand.CanExecute(null)) { vm.TextBlockMouseLeftButtonDownCommand.Execute(null) } } }
当您使用MVVM时,我建议您使用Galasoft MVVM Light Toolkit EventToCommand
我对这个问题的 回答没有任何外部工具包/库。 但是,它不使用RelativeSource
,而且它不是100%MVVM。 它在代码隐藏事件处理程序中需要一行代码。