views:

358

answers:

1

I have a Listbox with a UserControl as the DataTemplate. This UserControl has a button to remove that item from the list.

<ListBox x:Name="FileList" ItemsSource="{Binding Files}" >  
   <ListBox.ItemTemplate>
      <DataTemplate>
         <Views:FileItem/>
      </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

The ItemSource is defined as:

ObservableCollection<FileViewModel> m_fileViews = new ObservableCollection<FileViewModel>();

Here is the UserControl simplified

<UserControl x:Class="Views.FileItem">
   <Canvas x:Name="LayoutRoot">
      <TextBlock x:Name="FileName" Text="{Binding FileName}" />
      <Button Content="Remove"/>
   </Canvas>
</UserControl>

When the user clicks the Remove button, it should remove this item from the ObservableCollection.

The problem is, the DataContext for each ListBoxItem is a different ViewModel than the ViewModel that holds the ObservableCollection.

I'm not sure how to bind the "Remove" button to an ICommand in the "parent" ViewModel. Any help would be appreciated. Thanks so much.

+1  A: 

I would bind the button to an ICommand in the UserControl's ViewModel, then send a message across to the parent ViewModel using loosely-coupled messaging (available in most Mvvm frameworks, like MvvmFoundation)

Let the parent VM register for the 'remove me' message, and update the ObservableCollection accordingly...

Hope this helps :)

IanR
Thanks. This helped a lot. I was worried about a couple more scenarios I was going to face in development, and the Mediator pattern solved all of them.
mattjf