Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding to View Model Property from within 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 objectID as the CommandParemeter. e.g.

// 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 above ViewModel class. 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 Hyperlink content is shown correctly but the Command never fires, I guess this is because it's looking for a Command within the MyClass object?

How can I bind to the UserControls DataContext.MyCommand rather than the MyClass.MyCommand that it is looking for?

like image 525
Fermin Avatar asked Dec 08 '10 11:12

Fermin


1 Answers

Unfortunately, we don't have the FindAncestor mode on the RelativeSource markup extension that WPF has, so you can't use that (this will be added in Silverlight 5). It's nasty, but you can give your UserControl element a name, and use ElementName binding to bind to the command on the object assigned to its DataContext.

For example:

<UserControl Name="root">

Then bind the command (using dot notation from the DataContext of the UserControl):

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

Give that a try.

like image 199
Chris Anderson Avatar answered Oct 16 '22 11:10

Chris Anderson