Binding to view a model property from an ItemsControl.ItemTemplate

I have a collection of objects and a command in my ViewModel.

I want to display a hyperlink for each of the objects in the collection and set the command of each hyperlink to the same command, passing in the object identifier as a parameter CommandParemeter. eg.

// View Model
public class MyViewModel : ViewModelBase
{
  // Raises PropertyChanged event, ommited here
  public List<MyClass> MyList {....}

  public RelayCommand<int> MyCommand {....}
}

I set the DataContext of my UserControl to the class above ViewModel. The XAML for this UserControl is as follows:

<UserControl>
  <ItemsControl ItemsSource="{Binding Path=MyList}">
    <ItemsControl.ItemsPanel>
      <ItemsPanelTemplate>
        <StackPanel />
      </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <ItemsControl.ItemTemplate>
      <DataTemplate>
        <HyperlinkButton Content="{Binding Path=Description}" Command="{Binding Path=MyCommand}" CommandParameter="{Binding Path=MyClassID}"/>
      </DataTemplate>
    </ItemsControl.ItemTemplate>
  </ItemsControl>
</UserControl>

The description for the contents of the hyperlink is displayed correctly, but the command never fires, I think this is because it is looking for the command in the MyClass object?

How can I bind to UserControls DataContext.MyCommand and not to MyClass.MyCommand that it is looking for?

+5
1

, FindAncestor RelativeSource, WPF, ( Silverlight 5). , UserControl ElementName , DataContext.

:

<UserControl Name="root">

( DataContext UserControl):

Command="{Binding Path=DataContext.MyCommand, ElementName=root}"

.

+6

All Articles