在样式中使用事件命令触发器

本文关键字:事件 命令 触发器 样式 | 更新日期: 2023-09-27 18:10:25

我正在尝试使用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;
                                  }));
    }
}

但是这个命令从来没有触发过,我不知道为什么?

p。在样式中引用库的原因是因为这种样式是从后面的代码动态加载的。这是遗留代码,我目前正试图转换为mvvm。

在样式中使用事件命令触发器

所以我之前绑定的方式有两个问题。首先,主要原因是该样式没有数据上下文。并且显然没有从实现样式的模板继承数据上下文。还有命令参数不正确

CommandParameter='{Binding RelativeSource={RelativeSource AncestorType={x:Type ig:EventSpan}}}'

被绑定到一个relaycommand,需要一个字符串参数,所以崩溃了。因此正确的命令参数是

CommandParameter='{Binding Path=EventEntry.Series.Tag, RelativeSource={RelativeSource AncestorType={x:Type ig:EventSpan}}}'