如何使用MVVM light wpf中的命令处理网格中的RoutedEvent

时间:2017-12-26 08:16:59

标签: c# wpf mvvm mvvm-light

我正在使用MVVM灯来重新编码我的代码。我的旧代码看起来像这样 -

<Grid x:Name="root" ButtonBase.Click="LayoutRoot_Click">

LayoutRoot_Click将处理来自子控件的所有RoutedEvent。 因为网格没有命令接口,所以像这样的新代码

<Grid x:Name="root" ButtonBase.Click="LayoutRoot_Click">
<i:Interaction.Triggers>
    <i:EventTrigger EventName="ButtonBase.Click">
        <mvvm:EventToCommand Command="{Binding InputCommand}" CommandParameter="{Binding ElementName=button1}" />
    </i:EventTrigger>
</i:Interaction.Triggers>

像这样的viewmodel -

public class SomeViewModel : ViewModelBase
{
    public SomeViewModel()
    {
        InputCommand = new RelayCommand(InputCode);
    }

    public ICommand InputCommand { get; set; }

    private void InputCode()
    {
        string input = string.Empty;
    }
}

但这不起作用。该命令没有获得RoutedEvent。

1 个答案:

答案 0 :(得分:1)

尝试添加PassEventArgsToCommand =&#34; True&#34;你的命令绑定

<Grid x:Name="root" ButtonBase.Click="LayoutRoot_Click">
<i:Interaction.Triggers>
    <i:EventTrigger EventName="ButtonBase.Click">
        <mvvm:EventToCommand Command="{Binding InputCommand}" CommandParameter="{Binding ElementName=button1}" PassEventArgsToCommand="True"/>
   </i:EventTrigger>
</i:Interaction.Triggers>

然后你的命令必须有一个正确类型的参数,我认为是RoutedEventArgs

public RelayCommand<RoutedEventArgs> SomeCommand { get; private set; }
    private void SomeCode(RoutedEvent routedEvent)
    {
        //Do something with the routed event
    }