我正在尝试使用Mvvm Light工具包将事件绑定到样式中的命令。
我目前的风格是:
<Style
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:controls='clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:d='http://schemas.microsoft.com/expression/blend/2008'
xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006'
xmlns:ig='http://schemas.infragistics.com/xaml'
xmlns:i='http://schemas.microsoft.com/expression/2010/interactivity'
xmlns:Command='clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4'
TargetType='ig:EventSpan'>
<Setter Property='Template'>
<Setter.Value>
<ControlTemplate TargetType='ig:EventSpan'>
<Grid Margin='0,2,0,2'>
<i:Interaction.Triggers>
<i:EventTrigger EventName='MouseEnter'>
<Command:EventToCommand Command='{Binding EventSpan_MouseEnter1}' CommandParameter='{Binding RelativeSource={RelativeSource AncestorType={x:Type ig:EventSpan}}}'/>
</i:EventTrigger>
<i:EventTrigger EventName='MouseLeave'>
<Command:EventToCommand Command='{Binding EventSpan_MouseLeave1}' CommandParameter='{Binding RelativeSource={RelativeSource AncestorType={x:Type ig:EventSpan}}}'/>
</i:EventTrigger>
</i:Interaction.Triggers>
<Rectangle RadiusX='0' RadiusY='0' Fill='{TemplateBinding Fill}' Stroke='{TemplateBinding Stroke}' StrokeThickness='0' Height='0' Margin='0, 0, 0, 0' VerticalAlignment='Top' />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
后面的代码示例是:
private RelayCommand<string> _eventSpan_MouseEnter;
public RelayCommand<string> EventSpan_MouseEnter1
{
get
{
return _eventSpan_MouseEnter
?? (_eventSpan_MouseEnter = new RelayCommand<string>(
sender =>
{
MouseOverLayer = sender;
}));
}
}
但这个命令永远不会触发,我无法理解为什么?
PS。在样式中引用库的原因是因为此样式是从代码后面动态加载的。这是我目前正在尝试转换为mvvm的遗留代码。
答案 0 :(得分:0)
所以我以前的方式有两个问题。首先,主要原因是该风格没有datacontext。并且显然没有从实现样式的模板继承datacontext。并且命令参数不正确。
CommandParameter='{Binding RelativeSource={RelativeSource AncestorType={x:Type ig:EventSpan}}}'
绑定到一个relaycommand,期望一个字符串参数,因此崩溃了。因此,正确的命令参数是
CommandParameter='{Binding Path=EventEntry.Series.Tag, RelativeSource={RelativeSource AncestorType={x:Type ig:EventSpan}}}'