how to use EventToCommand in a ItemContainerStyle?

2.2k views Asked by At
        <ListBox Grid.Row="1" ItemsSource="{Binding Source}" SelectedItem="{Binding SelectedItem,Mode=TwoWay}" DisplayMemberPath="Name">
        <ListBox.ItemContainerStyle>
            <Style>
                <EventSetter Event="ListBoxItem.MouseDoubleClick" Handler="DoubleClick" />
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>

This is how it works now. What should I do if I want to Bind every ListBoxItem's DoubleClick event to a RelayCommand?

2

There are 2 answers

0
SvenG On BEST ANSWER

This is the way I am using the MVVMLight EventToCommand feature.

If you have a doubleclick event hook to that. If that is not available take the (preview)mousedown and check the clickCount in the command args. A ClickCount of 2 corresponds to a double click.

Please note: I have my own RelayCommand Implementation. The one from the MVMMLight toolkit might look different.

XAML:

<interactivity:Interaction.Triggers>
    <interactivity:EventTrigger EventName="MouseDown">
        <mvvmLight:EventToCommand PassEventArgsToCommand="True" Command="{Binding MouseDownCommand}"></mvvmLight:EventToCommand>
    </interactivity:EventTrigger>
</interactivity:Interaction.Triggers>

ViewModel:

public ICommand MouseDownCommand
{
  get
  {
    if (_mouseDownCommand == null)
    {
      _mouseDownCommand = new RelayCommand(x => MouseDown(x as MouseButtonEventArgs));
    }
    return _mouseDownCommand;
  }
}

private void MouseDown(MouseButtonEventArgs e)
{
  if (e.ClickCount == 2)
  {
    // do stuff
  }
}
0
Jonathan Allen On

The best way to do this is to just use a normal event handler written in code-behind. If needed this can relay to a method or command on your model or view-model.

Tricks like using an EventToCommand behavior just cost you in terms of more complex XAML and a pretty high risk that you will leak memory. (This happens because EventToCommand listens to the CanExecuteChanged event even when it shouldn't.)