0
votes

I want to double-click to copy an item from a "shopping list" to a "shopping cart" list box. Right now, my model just has ObservableCollection of strings for each list, but eventually the objects will get more complex.

The ViewModel is mapped to the view using a DataTemplate. Right now, I just have a "Session" property on my ViewModel that is exposing my Session object in my Model that contains both ObservableCollections.

I tried this...

<ListBox Name="listBoxShopList" ItemsSource="{Binding Path=Session.Products}">
  <ListBox.ItemContainerStyle>
    <Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource {x:Type ListBoxItem}}">
      <EventSetter Event="MouseDoubleClick" Handler="ListBoxItemMouseDoubleClick"/>
    </Style>
  </ListBox.ItemContainerStyle>
</ListBox>
<ListBox Name="listBoxCart" ItemsSource="{Binding Path=Session.CartItems, UpdateSourceTrigger=PropertyChanged}"/>

From code-behind I do get the event and I can get the SelectedItem. But being new to MVVM, I cannot figure out how to add the item to the "Cart" collection. It seems like I should be able to access the ViewModel Session.CartItems directly since the View can. Is a parameterized command the way to go? If so, any recommended articles?

2

2 Answers

1
votes

In your event handler code-behind you could get the ViewModel like this:

var viewModel = DataContext as <YourViewModelType>;

And then transfer the selected item to the cart.
The preferred way to do it would be using a command, like DelegateCommand.

1
votes

Well, you get your handler (a part of view code) called on double click. Good so far.

Now, you need to inform the VM that double-click happened (or better put some semantics here: selection changed, shopping cart accepted, etc.) by invoking a command (preferred way), or communicating with the VM through DataContext (easy way). Your VM can update the ObservableCollection as appropriate, and the view will get the changes through the usual binding.