问题描述
我想为用户控件上的所有按钮分配相同的命令.我使用MVVM Light,并且尝试了所有组合.我也尝试使用EventSetter,但这不允许绑定到ViewModel中的命令
I want to assign the same command to all my buttons on my user control. I use MVVM Light and I have tried all combinations. I have also tried to use EventSetter, but this does not allow binding to a command in the ViewModel
以下是我要执行的操作的一个示例:<Style x:Key="CalculatorButton" TargetType="telerik:RadButton"> <Setter Property="Margin" Value="2"/> <Setter Property="Cursor" Value="Hand"/> <Style.Triggers> <i:EventTrigger EventName="Click"> <cmd:EventToCommand Command="{Binding ButtonClick}"/> </i:EventTrigger> </Style.Triggers> </Style>
Here is a sample of what I am trying to do:<Style x:Key="CalculatorButton" TargetType="telerik:RadButton"> <Setter Property="Margin" Value="2"/> <Setter Property="Cursor" Value="Hand"/> <Style.Triggers> <i:EventTrigger EventName="Click"> <cmd:EventToCommand Command="{Binding ButtonClick}"/> </i:EventTrigger> </Style.Triggers> </Style>
设计时间错误:无法将类型'EventTrigger'的值添加到类型'TriggerCollection'的集合或词典中.
Design Time error: A value of type 'EventTrigger' cannot be added to a collection or dictionary of type 'TriggerCollection'.
运行时错误:值\"System.Windows.Interactivity.EventTrigger \"的类型不是\"System.Windows.TriggerBase \",并且不能在此通用集合中使用
Runtime Error: The value \"System.Windows.Interactivity.EventTrigger\" is not of type \"System.Windows.TriggerBase\" and cannot be used in this generic collection
推荐答案
不幸的是,i:EventTrigger
与EventTrigger
不同.前者是System.Windows.Interactivity
的一部分,而后者是WPF的核心部分.由于EventToCommand
使用System.Windows.Interactivity
,因此您必须使用与Style.Triggers
不同的机制来以样式使用它.您可以使用此StackOverflow答案中所述的技术:
Unfortunately, an i:EventTrigger
is not the same thing as an EventTrigger
. The former is part of the System.Windows.Interactivity
and the latter is a core part of WPF. Since EventToCommand
uses System.Windows.Interactivity
, you'll have to use a different mechanism than Style.Triggers
to use it in a style. You can use my technique described in this StackOverflow answer:
这篇关于按钮样式的EventToCommand的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!