绑定到ItemsControl.ItemTemplate中的View Model属性

时间:2010-12-08 11:15:30

标签: silverlight data-binding xaml silverlight-4.0

我在ViewModel中有一组对象和一个命令。

我想为集合中的每个对象显示超链接,并将每个超链接的Command设置为相同的命令,并将objectID作为CommandParemeter传递。 e.g。

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

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

我将UserControl的DataContext设置为上面的ViewModel类。此UserControl的XAML如下:

<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>

正确显示了超链接内容的描述,但命令永远不会触发,我想这是因为它在MyClass对象中寻找一个命令?

如何绑定UserControls DataContext.MyCommand而不是它正在寻找的MyClass.MyCommand?

1 个答案:

答案 0 :(得分:6)

不幸的是,我们在WPF的RelativeSource标记扩展上没有FindAncestor模式,所以你不能使用它(这将在Silverlight 5中添加)。这很讨厌,但您可以为UserControl元素指定名称,并使用ElementName绑定绑定到分配给其DataContext的对象上的命令。

例如:

<UserControl Name="root">

然后绑定命令(使用UserControl的DataContext中的点表示法):

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

试一试。

相关问题